java文件下載

java文件下載


import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;


@Controller
public class Down {
    @ResponseBody
    @RequestMapping(value = "/d")
    public void down(HttpServletRequest request,HttpServletResponse response) {
        try {
            //獲取網站部署路徑(通過ServletContext對象),用於確定下載文件位置,從而實現下載  
            //String path=request.getSession().getServletContext().getRealPath("tmp");
            String path = "d:/tmp";
            File file = new File(path);
            //1.設置文件ContentType類型,這樣設置,會自動判斷下載文件類型  
            response.setContentType("application/octet-stream");
            //2.設置文件頭:最後一個參數是設置下載文件名
            String fileName = new String(file.getName().getBytes("gbk"), "iso-8859-1");
            response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
            //設置文件大小
            response.setContentLength((int) file.length());
            ServletOutputStream out;
            //通過文件路徑獲得File對象(假如此路徑中有一個download.pdf文件)  

            FileInputStream inputStream = new FileInputStream(file);

            //3.通過response獲取ServletOutputStream對象(out)  
            out = response.getOutputStream();

            int b = 0;
            byte[] buffer = new byte[512];
            while (b != -1) {
                b = inputStream.read(buffer);
                //4.寫到輸出流(out)中  
                out.write(buffer, 0, b);
            }
            inputStream.close();
            out.close();
            out.flush();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
發佈了23 篇原創文章 · 獲贊 9 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章