天天看點

web實作檔案下載下傳

package com.pang.response;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;

public class ServletDome01 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        1. 要擷取下載下傳檔案的路徑
        String filepath ="E:\\ideaworkspace\\javaweb-02-servlet\\Response\\target\\classes\\001.jpeg";
        System.out.println("下載下傳的檔案路徑是:"+filepath);
//        2. 下載下傳的檔案名是啥?
        String realpath =filepath.substring(filepath.lastIndexOf("\\")+1);
//        3. 設定想辦法讓浏覽器能夠支援下載下傳我們需要的東西
        resp.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(realpath,"UTF-8"));
//        4. 擷取下載下傳檔案的輸入流
        FileInputStream fi = new FileInputStream(filepath);
//        5. 建立緩沖區
        int len =0;
        byte[] buffer =new byte[1024];
//        6. 擷取OutputStream對象
        ServletOutputStream out =resp.getOutputStream();
//        7. 将FileOutputStream流寫入到buffer緩沖區
        while ((len=fi.read(buffer))>0){
            out.write(buffer,0,len);
        }
        fi.close();
        out.close();
    }

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