1. 程式人生 > >fastDFS+LibreOffice(三):呼叫後臺方法下載和A標籤直接下載

fastDFS+LibreOffice(三):呼叫後臺方法下載和A標籤直接下載

注意:

1)A標籤直接下載無法修改檔名,但比較簡單。有些情況下,沒有download屬性也會自動下載。

<a href="http://檔案連結" download="">下載</a>

2)有按鈕的時候不要使用<button>,用<input type="button"/>代替。因為在我做過的專案裡面,已經出現了兩次使用<button>無法響應事件或修改樣式的情況了,具體原因我也沒深究。

3)從fastdfs中獲取實際檔案,傳入的引數是fdfsGroup和fdfsPath


byte[] fileByte = fastDFSTemplate.loadFile(fdfsGroup,fdfsPath);

4)jsp完整程式碼

<input type="button" onclick="download('${attachment.fileName}','${attachment.fdfsGroup}','${attachment.fdfsPath}')"
class="downloadButton fontTypeTwo" value="下載"/>

5)JS程式碼


 /* 下載 */
function download(fileName,fdfsGroup,fdfsPath) {
    location.href ="${ctx}/info/notice/download?fileName="+fileName+"&fdfsGroup="+fdfsGroup+"&fdfsPath="+fdfsPath;
}

6)後臺完整程式碼

/**
	 * 下載
	 * @param fileName
	 * @param fdfsGroup
	 * @param fdfsPath
	 * @param response
	 */
	@RequestMapping(value = "download")
public void download(String fileName,String fdfsGroup,String fdfsPath,HttpServletResponse response){

		// 設定返回檔名
        try {
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + new String(fileName.getBytes("UTF8"), "ISO8859_1"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        try {
            // 從fastdfs中獲取實際檔案
            byte[] fileByte = fastDFSTemplate.loadFile(fdfsGroup,fdfsPath);
            // 輸出流
            OutputStream out = response.getOutputStream();
            // 直接輸出
            out.write(fileByte);
            out.close();
        } catch (FastDFSException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
}