java文件下載


在開發中遇到需要下載文件的需求,現在把文件下載整理一下。

  1. 傳統文件下載方式有超鏈接下載或者后台程序下載兩種方式。通過超鏈接下載時,如果瀏覽器可以解析,那么就會直接打開,如果不能解析,就會彈出下載框;而后台程序下載就必須通過兩個響應頭和一個文件的輸入流。
  2. 后台程序下載
    • 兩個響應頭:
      • Content-Type:其值有比如 text/html;charset=utf-8
      • Content-Disposition:其值為 attachment;filename=文件名 以附件形式打開
    • 流:需要獲取文件的輸入流,然后通過response對象的輸出流輸出到客戶端。

1.Spring-ResponseEntity響應json格式接口,進行下載文件

import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;

@RequestMapping(value = "/demoDown") //匹配的是href中的download請求
public ResponseEntity<byte[]> download(HttpServletRequest request, @RequestParam("filename") String filename,Model model) throws IOException {

        String downloadFilePath = 			  				                      request.getSession().getServletContext().getRealPath("uploadbill");

        filename = new String(filename.getBytes("ISO-8859-1"), "UTF-8");
        //新建一個文件
        File file = new File(downloadFilePath + File.separator + filename);
		//http頭信息
        HttpHeaders headers = new HttpHeaders();
		//設置編碼
        String downloadFileName = new String(filename.getBytes("UTF-8"), "iso-8859-1");

        headers.setContentDispositionFormData("attachment", downloadFileName);
		//MediaType:互聯網媒介類型  contentType:具體請求中的媒體類型信息
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
      
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);

    }
<!-- 上傳組件包 上傳時需要這兩個依賴包,下載時可以不需要(如果以第一種方式進行下載文件則需要)-->
<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3.1</version>
</dependency>
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.4</version>
</dependency>

2.以流的方式下載

public HttpServletResponse download(String path, HttpServletResponse response) {
        try {
            // path指要下載的文件的路徑。
            File file = new File(path);
            // 取得文件名
            String filename = file.getName();
            // 取得文件的后綴名
            String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();

            // 獲取一個輸入流
            InputStream fis = new BufferedInputStream(new FileInputStream(path));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            // 設置響應信息
            // 設置response的Header
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
            response.addHeader("Content-Length", "" + file.length());
            // 設置內容類型
            response.setContentType("application/octet-stream");
            //獲取輸出流,然后寫出到客戶端
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());            
            toClient.write(buffer);
            //強制寫出
            toClient.flush();
            //關閉流
            toClient.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return response;
    }

3.下載本地文件

public void downloadLocal(HttpServletResponse response) throws FileNotFoundException {
        //文件的默認保存名
        String fileName = "Operator.doc".toString();
    	// 文件的存放路徑
        String filePath="c:/Operator.doc";
        // 讀到流中
        InputStream inStream = new FileInputStream(filePath);
        // 設置輸出的格式
        response.reset();
        response.setContentType("bin");
        response.addHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
        // 循環取出流中的數據
        byte[] b = new byte[1024];
        int len;
        try {
            while ((len = inStream.read(b)) > 0){
                response.getOutputStream().write(b, 0, len);
            }
            inStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

4.下載網絡文件

public void downloadNet(HttpServletResponse response) throws MalformedURLException {
    
    	//網絡地址
        String urlPath="windine.blogdriver.com/logo.gif";
        URL url = new URL(urlPath);

        try {
            URLConnection conn = url.openConnection();
            InputStream inStream = conn.getInputStream();
            FileOutputStream fs = new FileOutputStream("c:/abc.gif");

            byte[] buffer = new byte[1024];
            int byteread = 0;
            while ((byteread = inStream.read(buffer)) != -1) {
                fs.write(buffer, 0, byteread);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

5.支持在線打開的方式

public void downLoad(String filePath, HttpServletResponse response, boolean isOnLine) throws Exception {
        File f = new File(filePath);
        if (!f.exists()) {
            response.sendError(404, "File not found!");
            return;
        }
        BufferedInputStream br = new BufferedInputStream(new FileInputStream(f));
        byte[] buf = new byte[1024];
        int len = 0;

        response.reset();
    	// 在線打開方式
        if (isOnLine) { 
            URL u = new URL("file:///" + filePath);
            response.setContentType(u.openConnection().getContentType());
            response.setHeader("Content-Disposition", "inline; filename=" + f.getName());
            // 文件名應該編碼成UTF-8
        } else {
            // 純下載方式
            response.setContentType("application/x-msdownload");
            response.setHeader("Content-Disposition", "attachment; filename=" + f.getName());
        }
        OutputStream out = response.getOutputStream();
        while ((len = br.read(buf)) > 0){
             out.write(buf, 0, len);
        }
           
        br.close();
        out.close();
    }

注意事項:要進行文件下載操作,不能用ajax請求來下載文件。

6.參考博文

(1)https://www.cnblogs.com/lucas1024/p/9533220.html(java下載文件的幾種方式)
(2)https://blog.csdn.net/tuesdayma/article/details/79506432(不能使用ajax請求來進行下載文件)
(3)https://blog.csdn.net/yqs_love/article/details/51959776(拒絕訪問、找不到指定路徑問題解決)
(4)https://blog.csdn.net/loophome/article/details/86006812(Spring-ResponseEntity響應json格式接口)
(5)https://blog.csdn.net/qq_36537546/article/details/88421680(File.separator 詳解)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM