栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

SpringBoot:使用Apache Commons FileUpload的大型流文件上传

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SpringBoot:使用Apache Commons FileUpload的大型流文件上传

感谢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    ...}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/407860.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号