原生Servlet文件上傳和下載Servlet多個文件上傳

轉載:原文鏈接https://blog.csdn.net/HaHa_Sir/article/details/81744629
1、前端 html 代碼

<center>
    <h2> 基於servelt 3.0註解實現文件上傳 </h2>
    <h3>一、單個文件上傳</h3>
    <form action="${ctx }/uploadServlet" method="post" enctype="multipart/form-data">
        文件: <input type="file" name="uploadfile" ><br><br><br>
        <button type="submit" >提交</button>
    </form>
    <hr>
    <h3>二、 多個文件上傳</h3>
    <form action="${ctx }/uploadServlet" method="post" enctype="multipart/form-data">
        文件1: <input type="file" name="uploadfile" >
        文件2: <input type="file" name="uploadfile" >
        文件3: <input type="file" name="uploadfile" ><br><br><br>
        <button type="submit" >提交</button>
    </form>
</center>
2、uploadServlet 後端上傳部分代碼

import java.io.File;
import java.io.IOException;
import java.util.Collection;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
/**
* 文件上傳servlet
*/
@WebServlet("/uploadServlet")
// 該註解 將該Servlet 標記爲一個文件上傳的 servlet
@MultipartConfig
public class UploadServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 一、 獲取文件的存儲路徑
        String realPath =         request.getServletContext().getRealPath(File.separator+"userfiles");
        File file = new File(realPath);
        if(!file.exists()){
            file.mkdirs();
            System.out.println("路徑: "+realPath +" 建立成功!");
        }
 
        // 二、獲取上傳文件對象的集合
        Collection<Part> partList = request.getParts();
        if(partList.size() == 1){
            // 單個文件上傳
            Part part = request.getPart("uploadfile");
            // 獲取header 如: form-data; name="uploadfile"; filename="2018-08-11 開【華夏視訊網首發hxsxw.com】.mkv"
            String header = part.getHeader("content-disposition");
            // 獲取文件名
            String fileName = header.split(";")[2].split("=")[1].replaceAll("\"", "");
            // 執行寫入操做 --- 上傳到指定的目錄
            part.write(realPath+File.separator+fileName);
 
        }else{
            for (Part part : partList) {
                // 多個文件上傳
                String header = part.getHeader("content-disposition");
                String fileName = getFileName(header);
                part.write(realPath+File.separator+fileName);
            }
        }
        request.setAttribute("message", "文件上傳成功!");
        request.getRequestDispatcher("/WEB-INF/views/client/message.jsp").forward(request, response);
 
}
 
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
 
    /**
    * 根據請求頭解析出文件名
    * 請求頭的格式:火狐和google瀏覽器下:form-data; name="file"; filename="snmp4j--api.zip"
    * IE瀏覽器下:form-data; name="file"; filename="E:\snmp4j--api.zip"
    * [@param](https://my.oschina.net/u/2303379) header 請求頭
    * [@return](https://my.oschina.net/u/556800) 文件名
    * [@see](https://my.oschina.net/weimingwei) https://www.cnblogs.com/xdp-gacl/p/4224960.html
    * @date 2018年8月12日 22:57:27
    */
    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;
    }
}
3、DownLoadServlet 文件下載

一、使用 response.getOutputStream(); 返回二進制數據流,實現文件下載

二、 代碼以下:

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
/**
* 文件下載 servlet
*/
@WebServlet("/downloadServlet")
public class DownLoadServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 一、文件存放路徑
        String path="c:/";
        // 二、須要下載的文件名
        String fileName="default.png";
        File file = new File(path+fileName);
        response.reset();
        response.setCharacterEncoding("UTF-8");
        fileName = URLEncoder.encode(fileName, "UTF-8");
        response.setHeader("Content-Disposition", "attachment;fileName="+fileName);
        InputStream input = new FileInputStream(file);
        ServletOutputStream out = response.getOutputStream();
        byte[] buff =new byte[1024];
        int len ;
        while((len = input.read(buff)) != -1){
            out.write(buff, 0, len);
            out.flush();
        }
        input.close();
        out.close();
    }
 
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
 
}
相關文章
相關標籤/搜索