點選 按鈕 下載圖片
阿新 • • 發佈:2019-01-14
a 便籤的 連結需要 指向的action 返回的是 流
@ApiOperation(value="圖片下載",notes="") @RequestMapping(value="downPhoto",method=RequestMethod.GET) public void downPhoto( @RequestParam(value = "tid") Long tid, HttpServletRequest request, HttpServletResponse response ) throws BusinessException{ Photo photo = photoService.findPhoto(tid).getObject(); photoService.updatePhotoDownNum(tid); String url = fileUploadPath+photo.getUrl(); String ext = url.substring(url.lastIndexOf(".")); //獲取檔名 Long filename = new Date().getTime(); //設定響應頭和下載儲存的檔名 response.setContentType("APPLICATION/OCTET-STREAM"); //如果圖片名稱是中文需要設定轉碼 //response.setHeader("content-disposition", "attachment;fileName="+URLEncoder.encode(fileName, "UTF-8")); response.setHeader("Content-Disposition", "attachment; filename=\"" + filename+ext + "\""); try { //開啟指定檔案的流資訊 OutputStream outputStream = response.getOutputStream(); InputStream inputStream = new FileInputStream(url); byte[] buffer = new byte[1024]; int i = -1; while ((i = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, i); } outputStream.flush(); outputStream.close(); inputStream.close(); } catch (IOException e) { e.printStackTrace(); } }
// js 程式碼
$("[name='downloadButton']").on("click",function(){ var tid = $(this).attr("tid"); var empId = $(this).attr("empId"); if(userId == '' || !userId){ alert("請先登入!"); window.location = basePath; } var url = basePath+"/m/photo/downPhoto?tid="+tid; //console.log(url); //這裡 是先建立 <a>標籤,在a標籤裡面需要有一個 便籤,裡面的標籤相對隨意,比如:span標籤, //因為如果 只有 a 會用瀏覽器開啟 圖片 //注意我們 點選事件 是在 內部的標籤觸發的,通過事件冒泡傳遞給了 a,這樣就可以直接 下載檔案了 var aa = $("<a href="+url+" id='forDownPhoto' ><p></p></a>"); $(this).parent().append(aa); aa.find("p").trigger("click");//觸發內部的標籤點選事件 aa.remove();//移除a標籤 })