gpt4 book ai didi

java - 无法将 jquery ajax FormData 与 servlet 一起使用

转载 作者:行者123 更新时间:2023-12-02 02:34:32 28 4
gpt4 key购买 nike

我试图向 servlet 发出 ajax 请求,以使用 jquery ajax FormData 上传图像。但我总是从 servlet 收到错误响应。下面是我的代码:

JSP文件

 <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<title>File Upload</title>
<script>
function hitThis(){
alert("hello");
var form1 = document.getElementById("form1");
$.ajax( {
url: 'UploadDocs',
type: 'POST',
data: new FormData( form1 ),
processData: false,
contentType: false,
success: function(response) {
alert("success : ");
},
error: function(xhr) {
alert("error : "+JSON.stringify(xhr));
//Do Something to handle error
}

} );
}
</script>
</head>
<body>
<center>
<h1>File Upload</h1>
<form id="form1" class="form-inline" onsubmit="hitThis();">

Amount : <input type="text" value="232" name="amount"/><br>

Select file to upload: <input type="file" name="file" size="60" /><br />
Select file to upload: <input type="file" name="file" size="60" /><br />

<br /> <input type="submit" value="Upload" />
</form>
</center>
</body>
</html>

Servlet

package org.wpits.ussd;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.json.JSONObject;
import org.wpits.service.DbService;
import org.wpits.ussd.beans.UserDocs;

/**
* Servlet implementation class UploadDocs
*/
@WebServlet("/UploadDocs")
@MultipartConfig(fileSizeThreshold=1024*1024*2, // 2MB
maxFileSize=1024*1024*10, // 10MB
maxRequestSize=1024*1024*50) // 50MB
public class UploadDocs extends HttpServlet {
private static final long serialVersionUID = 1L;
private DbService dbService = new DbService();
private String filePath;

public UploadDocs() {
super();
}

@Override
public void init(ServletConfig config) throws ServletException {
// TODO Auto-generated method stub
super.init(config);
filePath = getServletContext().getInitParameter("file-upload");
}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
String savePath = filePath;
String amount = request.getParameter("amount");
System.out.println(amount);
File fileSaveDir = new File(savePath);
if (!fileSaveDir.exists()) {
fileSaveDir.mkdir();
}

for (Part part : request.getParts()) {
String fileName = extractFileName(part);
if(fileName!=null && !fileName.equals("")){
InputStream is = part.getInputStream();
File f = new File(savePath+File.separator+fileName);
copyInputStreamToFile(is,f);
}
}
}

private void copyInputStreamToFile( InputStream in, File file ) {
try {
OutputStream out = new FileOutputStream(file);
byte[] buf = new byte[1024*1024*10];
int len;
while((len=in.read(buf))>0){
out.write(buf,0,len);
}
out.flush();
out.close();
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}

private String extractFileName(Part part) {
String contentDisp = part.getHeader("content-disposition");
String[] items = contentDisp.split(";");
for (String s : items) {
if (s.trim().startsWith("filename")) {
return s.substring(s.indexOf("=") + 2, s.length()-1);
}
}
return "";
}
}

我能够在描述的目录路径上写入图像。但问题是,我总是被重定向到 ajax 的错误响应。另外,每当我重新启动 tomcat 服务器并尝试上传文件时,我都会收到“java.io.IOException: org.apache.tomcat.util.http.fileupload.FileUploadBase$IOFileUploadException: 处理 multipart/form-数据请求失败。流意外结束”在第一次尝试因错误失败后的第二次尝试中,上面编写的代码能够写入文件,但会抛出对 Ajax 错误函数的响应。我哪里出错了?如果有人能解决我的问题,那将非常有帮助。

最佳答案

使用此格式来触发 ajax。

//get choosen file
var fileContent = new FormData();
fileContent.append("file",$('input[type=file]')[0].files[0]);
$.ajax({
type: "POST",
enctype:"multipart/form-data",
url: "uploadCsvData",
data: fileContent,
processData: false,
contentType: false,
success: function(response) {
}
});

关于java - 无法将 jquery ajax FormData 与 servlet 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46580612/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com