【发布时间】:2020-10-17 23:20:51
【问题描述】:
过去几天我一直被这个问题困扰,没有其他帖子有帮助。 我正在尝试在看起来像这样的 HTML 表单上上传文件(它包含其他字段):
```
然后通过 FormData 将其上传到使用 Ajax:
var formData = new FormData();
formData.append('file', $('#file')[0].files[0]);
$.ajax({
url: './upload',
cache: false,
processData: false,
contentType: false,
method: 'POST',
data: formData,
dataType: 'json'
})
然后,在服务器端,我想检索文件并使用 httpServlet 保存它,我正在使用我从 Oracle 文档“改编”的这段代码:
@WebServlet(name = "FileUploadServlet", urlPatterns = {"/upload"})
@MultipartConfig
public class FileUploadServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
// Create path components to save the file
final String path = "C:\\Users\\me\\Desktop";
final Part filePart = request.getPart("file");
final String fileName = "myFile";
OutputStream out = null;
InputStream filecontent = null;
final PrintWriter writer = response.getWriter();
try {
out = new FileOutputStream(new File(path + File.separator
+ fileName));
filecontent = filePart.getInputStream();
int read = 0;
final byte[] bytes = new byte[1024];
while ((read = filecontent.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
writer.println("New file " + fileName + " created at " + path);
} catch (FileNotFoundException fne) {
writer.println("You either did not specify a file to upload or are "
+ "trying to upload a file to a protected or nonexistent "
+ "location.");
writer.println("<br/> ERROR: " + fne.getMessage());
} finally {
if (out != null) {
out.close();
}
if (filecontent != null) {
filecontent.close();
}
if (writer != null) {
writer.close();
}
}
}
但是我在 Ajax 调用中遇到了一个错误(我正在处理其他字段,并通过另一个 ajax 调用另一个 servlet 工作得很好,因为它们是文本字段)。
我觉得问题一定出在服务器端,因为我在客户端使用的代码我随处可见。
任何提示将不胜感激!
谢谢!
编辑: 实际上使用此代码文件已正确保存,但仍然存在 Ajax 错误
【问题讨论】:
-
你在 ajax 中遇到了什么错误?
-
我有
.fail(function (error) { console.log('Error', error); alert("Erreur lors de l'appel AJAX"); })ajax调用后,这段代码被调用 -
console.log('Error', error);在控制台中提供了什么?
标签: html jquery ajax file-upload form-data