
感谢M.Deinum的一些非常有帮助的评论,我设法解决了这个问题。我已经整理了一些原始帖子,并将其作为完整答案发布,以备将来参考。
我犯的第一个错误是没有禁用
MultipartResolverSpring提供的默认值。这最终导致解析器处理
HttpServeletRequest并因此在我的控制器对其执行 *** 作之前将其消耗掉。
感谢M. Deinum,禁用它的方法如下:
multipart.enabled=false
但是,此后还有另一个隐患等待着我。禁用默认的多部分解析器后,尝试进行上传时,我开始出现以下错误:
Fri Sep 25 20:23:47 IST 2015There was an unexpected error (type=Method Not Allowed, status=405).Request method 'POST' not supported
在我的安全配置中,我启用了CSRF保护。这就需要我以以下方式发送POST请求:
<html><body><form method="POST" enctype="multipart/form-data" action="/upload?${_csrf.parameterName}=${_csrf.token}"> <input type="file" name="file"><br> <input type="submit" value="Upload"></form></body></html>我还对控制器做了一些修改:
@Controllerpublic class FileUploadController { @RequestMapping(value="/upload", method=RequestMethod.POST) public @ResponseBody Response<String> upload(HttpServletRequest request) { try { boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (!isMultipart) { // Inform user about invalid request Response<String> responseObject = new Response<String>(false, "Not a multipart request.", ""); return responseObject; } // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(); // Parse the request FileItemIterator iter = upload.getItemIterator(request); while (iter.hasNext()) { FileItemStream item = iter.next(); String name = item.getFieldName(); InputStream stream = item.openStream(); if (!item.isFormField()) { String filename = item.getName(); // Process the input stream OutputStream out = new FileOutputStream(filename); IOUtils.copy(stream, out); stream.close(); out.close(); } } } catch (FileUploadException e) { return new Response<String>(false, "File upload error", e.toString()); } catch (IOException e) { return new Response<String>(false, "Internal server IO error", e.toString()); } return new Response<String>(true, "Success", ""); } @RequestMapping(value = "/uploader", method = RequestMethod.GET) public ModelAndView uploaderPage() { ModelAndView model = new ModelAndView(); model.setViewName("uploader"); return model; }}其中Response只是我使用的一种简单的通用响应类型:
public class Response<T> { private boolean status; private String message; private T data; public Response(boolean status, String message, T data) { this.status = status; this.message = message; this.data = data; } // Setters and getters ...}欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)