根据dojo教程和此处的几个示例,我试图发送多个文件帮助。 servlet的文件将到达目录,但是dojo将返回异常
我使用dojo 1.10和javax.servlet.http.HttpServlet v3.0.1
PrintWriter out = response.getWriter();
try {
if (ServletFileUpload.isMultipartContent(request)) {
try {
@SuppressWarnings("unchecked")
List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
for (FileItem item : multiparts) {
if (!item.isFormField()) {
String name = new File(item.getName()).getName();
item.write(new File("/tmp/eshop/" + File.separator + name));
}
}
out.print("[{uploadresult:'Upload is ok!'}]");
} catch (Exception ex) {
out.print("{uploadresult: 'File upload failed due to : '" + ex+"}");
}
} else {
out.print("{uploadresult:'Sorry this servlet only handles file upload request.'}");
}
out.close();
} catch (Exception e) {
logger.error(e);
}
引发错误:
/dojo/v1.10/dojox/form/uploader/_HTML5.js:80解析服务器时出错 结果:SyntaxError:JSON中位置2处的意外令牌u 在JSON.parse() 在Object.eval(/dojo/v1.10/dojox/form/uploader/_HTML5.js:76) 在XMLHttpRequest。 (dojo.js:15)(匿名)@ /dojo/v1.10/dojox/form/uploader/_HTML5.js:80 /dojo/v1.10/dojox/form/uploader/_HTML5.js:81 [{uploadresult:'上传 可以!'}]
答案 0 :(得分:0)
首先,将响应设置为json格式
首先添加response.setContentType("application/json");
您必须通过在引号中添加引号来正确格式化json:
response.setContentType("application/json");
PrintWriter out = response.getWriter();
try {
if (ServletFileUpload.isMultipartContent(request)) {
try {
@SuppressWarnings("unchecked")
List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
for (FileItem item : multiparts) {
if (!item.isFormField()) {
String name = new File(item.getName()).getName();
item.write(new File("/tmp/eshop/" + File.separator + name));
}
}
out.print("[{'uploadresult':'Upload is ok!'}]");
} catch (Exception ex) {
out.print("{'uploadresult': 'File upload failed due to : '" + ex+"}");
}
} else {
out.print("{'uploadresult':'Sorry this servlet only handles file upload request.'}");
}
out.close();
} catch (Exception e) {
logger.error(e);
}