Java学习笔记

文件上传

2016-11-30  本文已影响66人  Czw_hacker

commons-fileupload文件上传

@WebServlet("/upload")
public class FileUploadServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("upload.jsp").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //文件保存路径
        File saveDir = new File("D:/upload");
        if (!saveDir.exists()) {
            saveDir.mkdir();
        }
        //文件缓存路径
        File tempDir = new File("D:/tp");
        if (!tempDir.exists()) {
            tempDir.mkdir();
        }

        //判断表单是否有entype属性
        if (ServletFileUpload.isMultipartContent(req)) {

            DiskFileItemFactory itemFactory = new DiskFileItemFactory();
            itemFactory.setSizeThreshold(1024);//设置缓冲区大小
            itemFactory.setRepository(tempDir);//设置临时文件路径

            //获取ServletFileUpload对象,设置文件最大上传大小
            ServletFileUpload servletFileUpload = new ServletFileUpload(itemFactory);
            servletFileUpload.setFileSizeMax(1024 * 1024 * 10);

            try {
                //获取所有表单元素(普通元素+文件元素)返回值为FileItem对象数组
                List<FileItem> fileItemList = servletFileUpload.parseRequest(req);
                for (FileItem fileItem : fileItemList) {
                    if (fileItem.isFormField()) {
                        //普通元素
                        System.out.println("getFieldName ->" + fileItem.getFieldName());//获取普通元素name属性的值
                        System.out.println("getString ->" + fileItem.getString("UTF-8"));//获取普通元素文本框输入的值

                    } else {
                        //文件元素
                        System.out.println("getFieldName ->" + fileItem.getFieldName());//获取文件元素name属性的值
                        System.out.println("getName ->" + fileItem.getName());//获取文件的初始名

                        String uuid = UUID.randomUUID().toString();
                        String name = uuid + fileItem.getName().substring(fileItem.getName().lastIndexOf("."));

                        //获取文件输入流
                        InputStream inputStream = fileItem.getInputStream();
                        FileOutputStream outputStream = new FileOutputStream(new File(saveDir, name));

                        IOUtils.copy(inputStream, outputStream);
                      /* byte[] buffer = new byte[1024];
                       int len = -1;
                       while ((len = inputStream.read(buffer))!=-1){
                            outputStream.write(buffer,0,len);
                       }*/
                        outputStream.flush();
                        outputStream.close();
                        inputStream.close();
                        System.out.println("上传成功");
                    }
                }
            } catch (FileUploadException e) {
                e.printStackTrace();
            }
        } else {
            System.out.println("文件上传失败");
        }
   }
}

jsp代码

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>

<%--文件上传method方法必须为post
enctype属性值必须为multipart/form-data--%>

<form action="/upload" method="post" enctype="multipart/form-data">
    <input type="text" name="desc"> <br>
    <input type="file" name="file"> <br>
    <button>上传</button>
</form>
</body>
</html>

Servlet3文件上传

@WebServlet("/upload2")
@MultipartConfig
public class FileUploadServlet2 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("upload2.jsp").forward(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        String desc = req.getParameter("dasc");

        //通过name属性获取Part对象
        Part part = req.getPart("file");
        System.out.println("getname ->"+part.getName());//name属性值
        System.out.println("ContentType ->"+part.getContentType());//文件的MIME类型
        System.out.println("Size ->"+part.getSize());//文件大小(字节)
        System.out.println("SubmittedFileName ->"+part.getSubmittedFileName());//文件上传名字

        FileUtils.byteCountToDisplaySize(part.getSize());
        File saveDir = new File("D:/upload");
        if(saveDir.exists()){
            saveDir.mkdir();
        }

        String fileName = part.getSubmittedFileName();

        String uuid = UUID.randomUUID().toString();
        String name = uuid + fileName.substring(fileName.lastIndexOf("."));

        InputStream inputStream = part.getInputStream();
        FileOutputStream outputStream = new FileOutputStream(new File(saveDir,name));
        IOUtils.copy(inputStream,outputStream);

        outputStream.flush();
        outputStream.close();
        inputStream.close();
        System.out.println("成功");
    }
}
上一篇下一篇

猜你喜欢

热点阅读