• Java Servlet 接收上传文件


    在Java中使用 Servlet 来接收用户上传的文件,需要用到两个apache包,分别是 commons-fileupload 和 commons-io 包;

    如果直接在doPost中,使用request.getInputStream()获取ServletInputStream,这样获取到的Stream是不能直接写入文件的,比如上传一个txt文件,你会发现保存下来的txt文件不只有原本txt文件本身的内容,里面还有post请求的一些参数,比如参数分割符等;

    下面就是一个使用fileupload包来接收文件内容的例子:

    public class FileServlet extends HttpServlet {
        /**
         * 
         */
        private static final long serialVersionUID = -4187075130535308117L;
        private boolean isMultipart;
        private int maxFileSize = 1024 * 1024 * 10;
        private int maxMemSize = 100 * 1024;
    
        @Override
        protected void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            // 检查是否有一个文件上传请求
            isMultipart = ServletFileUpload.isMultipartContent(request);
            String result = "";
            response.setContentType("text/html;charset=utf-8");
            if (!isMultipart) {
                result = "未获取到文件";
                response.getWriter().println(result);
                return;
            }
            DiskFileItemFactory factory = new DiskFileItemFactory();
            // 文件大小的最大值将被存储在内存中
            factory.setSizeThreshold(maxMemSize);
            // Location to save data that is larger than maxMemSize.
            String path = getServletContext().getRealPath("/") + "/";
            factory.setRepository(new File(path));
            // System.out.println(path);
            // 创建一个新的文件上传处理程序
            ServletFileUpload upload = new ServletFileUpload(factory);
            // 允许上传的文件大小的最大值
            upload.setSizeMax(maxFileSize);
    
            try {
                // 解析请求,获取文件项
                List fileItems = upload.parseRequest(request);
                // 处理上传的文件项
                Iterator i = fileItems.iterator();
                while (i.hasNext()) {
                    FileItem fi = (FileItem) i.next();
                    if (!fi.isFormField()) {
                        // 获取上传文件的参数
                        String fieldName = fi.getFieldName();
                        String fileName = fi.getName();
                        String contentType = fi.getContentType();
                        boolean isInMemory = fi.isInMemory();
                        long sizeInBytes = fi.getSize();
                        // 写入文件
                        File file = new File(path + System.currentTimeMillis() / 1000 + ".py");
                        fi.write(file);
                    }
                }
                result = "上传成功";
            } catch (Exception ex) {
                System.out.println("ex:" + ex.getMessage());
                result = "上传失败";
            }
    
            response.getWriter().println(result);
        }
    }

    接下来,在html页面中,可以通过在一个表单中来提交上传文件

        <form action="fileUpload" enctype="multipart/form-data" method="post">
            <input type="file" name="file"></input> <input type="submit"
                value="提交"></input>
        </form>
  • 相关阅读:
    tableView
    ios设计模式 设计一个应用程序 笔记
    Touching the Background to close the Keyboard
    fdfd
    fdffafadf
    Declaring the Action Method
    网易公开课IOS笔记 第二课
    getters and setters
    objective c
    Google编码规范 C++ Style Guide, JavaScript Style Guide, ObjectiveC Style Guide, and Python Style Guide
  • 原文地址:https://www.cnblogs.com/284628487a/p/5579936.html
Copyright © 2020-2023  润新知