java servlet 文件上传 - 2018
原创    java_world    发表于:2018-04-27 10:41:59
  阅读 :113   收藏   编辑

依赖:

  • commons-io-2.4.jar
  • fileupload-1.2.1.jar

upload.jsp

<%@ page language="java" contentType="text/html;charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html >
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title> servlet 文件上传</title>
</head>
<body>
    <form action="uploadServlet" method="post" enctype="multipart/form-data">
        fileName:<input type="text" name="fileName"/><br/>
        file:<input type="file" name="file"><br/>
        <input type="submit" value="上传">
    </form>
</body>
</html>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    version="2.5">

    <servlet>
        <servlet-name>uploadServlet</servlet-name>
        <servlet-class>com.xx.UploadServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>uploadServlet</servlet-name>
        <url-pattern>/uploadServlet</url-pattern>
    </servlet-mapping>
</web-app>

UploadServlet.java

package com.xx;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

@SuppressWarnings("serial")
public class UploadServlet extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        /**
         * 编码格式
         */
        request.setCharacterEncoding("UTF-8");  
        response.setContentType("text/html;charset=UTF-8");  

        /**
         * 获取流
         */
        PrintWriter pw = response.getWriter();  
        try {  
            DiskFileItemFactory factory = new DiskFileItemFactory();  

            /**
             * 获取项目webapp目录下的upload的路径
             */
            String prePath  = request.getSession().getServletContext().getRealPath("/files");

            System.err.println("prePath:" + prePath);

            /**
             * 判断传输方式
             */
            boolean isMultipart = ServletFileUpload.isMultipartContent(request);  
            if(!isMultipart)   {  
                pw.write("传输方式有错误!");  
                return;  
            }  
            ServletFileUpload upload = new ServletFileUpload(factory);  
            upload.setFileSizeMax(1*1024*1024);//设置单个文件大小不能超过1M  
            upload.setSizeMax(4*1024*1024);//设置总文件上传大小不能超过4M  

            /**
             * 解析
             */
            List<FileItem> items = upload.parseRequest(request);  
            for(FileItem item: items){  
                /**
                 * 普通字段
                 */
                if(item.isFormField())
                {  
                    String name = item.getFieldName();  
                    String value = item.getString("UTF-8");  
                    System.out.println(name + "--> " + value);  
                }else  
                {      

                    InputStream in =item.getInputStream();  
                    String fileName = item.getName();   
                    if(fileName==null || "".equals(fileName.trim())){  
                        continue;  
                    }  


                    System.err.println("文件名称---> " + fileName );

                    /**
                     * 文件类型
                     */
                    String fileType = fileName.substring(fileName.lastIndexOf("."),fileName.length());

                    System.err.println("文件类型---> " + fileType );


                    /**
                     * 上传保存后新的文件名称
                     */
                    String newFileName = UUID.randomUUID().toString() + fileType;

                    System.err.println("newFileName ---> " + newFileName);


                    File newFile = new File(prePath + File.separator + newFileName);

                    if(!newFile.getParentFile().exists()) {
                        /**
                         * 创建目录
                         */
                        newFile.getParentFile().mkdirs();
                    }

                    OutputStream out = new FileOutputStream(newFile);

                    /**
                     * copy 流,或  IOUtils.copy(input, output);
                     */

                    byte[] b = new byte[1024];  
                    int len = -1;  
                    while((len = in.read(b))!=-1)  
                    {  
                         out.write(b,0,len);          
                    }  



                    /**
                     * 清理
                     */
                    in.close();  
                    out.close();  

                    /**
                     * 删除临时文件  
                     */
                    item.delete();
                }  
              }  
        }catch(org.apache.commons.fileupload.FileUploadBase.FileSizeLimitExceededException e){   
            pw.write("单个文件不能超过1M");  
            e.printStackTrace();
        }catch(org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException e){  
            pw.write("总文件不能超过4M");  
            e.printStackTrace();

        }catch (FileUploadException e) {  
            e.printStackTrace();  
        }

    }

}

评论
条评论