本文介绍了中止从servlet上传以限制文件大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我想限制可以上传到应用程序的文件的大小。为了达到这个目的,当上传文件的大小超过限制时,我想从服务器端中止上传过程。I'd like to limit the size of the file that can be uploaded to an application. To achieve this, I'd like to abort the upload process from the server side when the size of the file being uploaded exceeds a limit.有没有办法可以中止从服务器端上传进程而不等待HTTP请求完成?Is there a way to abort an upload process from the server side without waiting the HTTP request to finish?推荐答案你可以这样做(使用 Commons library):You can do something like this (using the Commons library): public class UploadFileServiceImpl extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { response.setContentType("text/plain"); try { FileItem uploadItem = getFileItem(request); if (uploadItem == null) { // ERROR } // Add logic here } catch (Exception ex) { response.getWriter().write("Error: file upload failure: " + ex.getMessage()); } } private FileItem getFileItem(HttpServletRequest request) throws FileUploadException { DiskFileItemFactory factory = new DiskFileItemFactory(); // Add here your own limit factory.setSizeThreshold(DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD); ServletFileUpload upload = new ServletFileUpload(factory); // Add here your own limit upload.setSizeMax(DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD); List<?> items = upload.parseRequest(request); Iterator<?> it = items.iterator(); while (it.hasNext()) { FileItem item = (FileItem) it.next(); // Search here for file item if (!item.isFormField() && // Check field name to get to file item ... { return item; } } return null; } } 这篇关于中止从servlet上传以限制文件大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 08-05 05:57