08-文件上传

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/linzhaoliangyan/article/details/88621040

1 文件上传

    * common-fileupload

        * http://commons.apache.org/proper/commons-fileupload/download_fileupload.cgi 

        *  form:enctype="multipart/form-data"

        *  input: type=“file”

    * 下载common-fileupload和导包

        *  http://commons.apache.org/proper/commons-fileupload/download_fileupload.cgi

* 常见的API

        * ServletFileUpload(核心)

            * 构建的时候,需要DiskFileItemFactory

        * DiskFileItemFactory

        * FileItem

    * Hello 文件上传

  * 导入jar

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
    <h1>文件上传</h1>
    <form action="${pageContext.request.contextPath }/upload" method="post" enctype="multipart/form-data">
        <input type="text" name="username"/><br>
        <input type="file" name="file1"/><br>
        <input type="file" name="file2"/><br>
        <input type="submit" value="提交"/>
    </form>
</body>
</html>
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		  // 1 获取存储文件上传路径,假如不存在就创建
        String realPath = request.getServletContext().getRealPath("/WEB-INF/upload");
        File saveDir = new File(realPath);
        if (!saveDir.exists() || !saveDir.isDirectory()) {
            saveDir.mkdir();
        }
        // 2 构建DiskFileItemFactory
        DiskFileItemFactory dfif = new DiskFileItemFactory();
        // 3 构建ServletFileUpload
        ServletFileUpload upload = new ServletFileUpload(dfif);
        // 4 设置编码
        upload.setHeaderEncoding("UTF-8");
        // 6 通过请求获取FileItem的列表
        InputStream is = null;
        FileOutputStream out = null;
        try {
            List<FileItem> items = upload.parseRequest(request);
            for (FileItem item : items) {
                // 判断是文件上传还是普通文本域
                if (item.isFormField()) {
                    String fieldName = item.getFieldName();
                    String value = item.getString("UTF-8");
                    System.out.println(fieldName + ":" + value);
                    continue;
                }

                // 得到上传的文件名称,
                String filename = item.getName();
                System.out.println(filename);
                if (filename == null || filename.trim().equals("")) {
                    continue;
                }
                // 注意:不同的浏览器提交的文件名是不一样的,有些浏览器提交上来的文件名是带有路径的,如: c:\a\b\1.txt,而有些只是单纯的文件名,如:1.txt
                // 处理获取到的上传文件的文件名的路径部分,只保留文件名部分
                filename = filename.substring(filename.lastIndexOf("\\") + 1);
                is = item.getInputStream();
                out = new FileOutputStream(saveDir + "\\" + filename);
                IOUtils.copy(is, out, 1024 * 8);
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                is.close();
            }

            if (out != null) {
                out.close();
            }
        }

	}

1.5 Servlet3.0 文件上传

        * 在Servlet2.5中,我们要实现文件上传功能时,一般都需要借助第三方开源组件,例如Apache的commons-fileupload组件,在Servlet3.0中提供了对文件上传的原生支持,我们不需要借助任何第三方上传组件,直接使用Servlet3.0提供的API就能够实现文件上传功能了

      * @MultipartConfig

 * Collection<Part> parts=request.getParts();

/**
 * Servlet implementation class UploadServlet
 */
@WebServlet(name = "upload3", urlPatterns = { "/upload3" })
@MultipartConfig
public class UploadServlet3 extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public UploadServlet3() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        // 1 获取存储文件上传路径,假如不存在就创建
        String realPath = request.getServletContext().getRealPath("/WEB-INF/upload");
        File saveDir = new File(realPath);
        if (!saveDir.exists() || !saveDir.isDirectory()) {
            saveDir.mkdir();
        }
        Collection<Part> parts = request.getParts();
        for (Part part : parts) {
            String header = part.getHeader("content-disposition");
            System.out.println(header);
            String filename = getFileName(header);
            System.out.println(filename);
            part.write(realPath + File.separator + filename);
        }
        PrintWriter out = response.getWriter();
        out.println("上传成功");
        out.flush();
        out.close();
    }

    /**
     * 根据请求头解析出文件名 请求头的格式:火狐和google浏览器下:form-data; name="file";
     * filename="snmp4j--api.zip" IE浏览器下:form-data; name="file";
     * filename="E:\snmp4j--api.zip"
     * 
     * @param header
     *            请求头
     * @return 文件名
     */
    public String getFileName(String header) {
        /**
         * String[] tempArr1 = header.split(";");代码执行完之后,在不同的浏览器下,tempArr1数组里面的内容稍有区别
         * 火狐或者google浏览器下:tempArr1={form-data,name="file",filename="snmp4j--api.zip"}
         * IE浏览器下:tempArr1={form-data,name="file",filename="E:\snmp4j--api.zip"}
         */
        String[] tempArr1 = header.split(";");
        /**
         * 火狐或者google浏览器下:tempArr2={filename,"snmp4j--api.zip"}
         * IE浏览器下:tempArr2={filename,"E:\snmp4j--api.zip"}
         */
        String[] tempArr2 = tempArr1[2].split("=");
        // 获取文件名,兼容各种浏览器的写法
        String fileName = tempArr2[1].substring(tempArr2[1].lastIndexOf("\\") + 1).replaceAll("\"", "");
        return fileName;
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}

猜你喜欢

转载自blog.csdn.net/linzhaoliangyan/article/details/88621040