1. 程式人生 > >點選按鈕實現檔案下載

點選按鈕實現檔案下載

一、使用背景

一般來說,當我們上傳檔案之後,便會要提供檔案下載的入口。而其實檔案下載就是獲取檔案,並將檔案內容寫入到HTTP返回響應的過程。

二、前端實現方式

  • 構造form表單提交

1、引入相關js

<script src="${basepath}/jquery-3.3.1/jquery-3.3.1.js" type="text/javascript"></script>
<script src="${basepath}/downLoadFile.js" type="text/javascript" ></script>

2、在下載按鈕上繫結點選事件

<button onclick=downLoadFile('"+fileId+"') class='btn btn-info btn-sm pull-right'>下 載</button>

3、downLoadFile.js原始碼

function downLoadFile(id){
	var form=$("<form>");    // 定義一個form表單
	form.attr("style","display:none");
	form.attr("target","_blank");
	form.attr("method","post");
	form.attr("action","/download");    // 此處填寫檔案下載提交路徑
	var input1=$("<input>");
	input1.attr("type","hidden");
	input1.attr("name","id");    // 後臺接收引數名
	input1.attr("value",id);
	$("body").append(form);    // 將表單放置在web中
	form.append(input1);
	form.submit();    // 表單提交
}

三、後臺Java實現部分程式碼

/**
  * 附件下載
  */
@RequestMapping(value = "download")
public String downloadFile( HttpServletRequest request, Model model,HttpServletResponse response, RedirectAttributes redirectAttributes,String id) {
    shareFile = fileService.get(id);
    if(shareFile != null){
        String fileName = shareFile.getFilename().replace(" ", "");
        response.reset();
        response.setContentType("application/octet-stream; charset=utf-8");
        String agent = request.getHeader("USER-AGENT");    // 獲取瀏覽器型別
        String downLoadName = null;  
        try {
            // Edge
            if (null != agent && -1 != agent.indexOf("Edge")) {    
                downLoadName = java.net.URLEncoder.encode(fileName, "UTF-8");
            // Firefox
            } else if (null != agent && -1 != agent.indexOf("Firefox")) {        
                downLoadName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");
            // Chrome或360  
            } else if (null != agent && -1 != agent.indexOf("Chrome")) {        
                downLoadName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");     
            } else {  
                downLoadName = java.net.URLEncoder.encode(fileName, "UTF-8");   
            }   
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } 
        response.setHeader("Content-Disposition", "attachment; filename="+downLoadName);
		
        InputStream in = fileService.downloadFile(shareFile);    // 此處是獲取檔案輸入流 
        OutputStream out;
        try {
            out = response.getOutputStream();
            //寫檔案  
            int b;  
            while((b = in.read()) != -1) {  
                out.write(b);  
            }
            in.close();  
            out.close();  
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return null;
}