vue和springmvc下載文件親測的兩種方式


第一種:responseType: 'blob' ,這種方式用於文件在磁盤中

vue:

download(index,row){
var ts = this;
axios.post(this.paths.baseURL+'file/downloadFile',
{path:row.zurl},
{responseType: 'blob'}
).then(msg => {
let link = document.createElement("a");
link.style.display = "none";
link.href = window.URL.createObjectURL(new Blob([msg.data]));
link.setAttribute("download",row.zurl.substring(row.zurl.lastIndexOf("/")+1));//文件名
document.body.appendChild(link);
link.click();
URL.revokeObjectURL(link.href);
document.body.removeChild(link);
}).catch(error =>{
ts.$message.error('下載文件失敗')
})
},

 

java:

@RequestMapping(value = "downloadFile",method = RequestMethod.POST,produces = {"application/json;charset = utf-8"})
@ApiOperation(notes = "下載",value = "下載")
@RequiresPermissions("file:download")
public ResponseEntity<byte[]> downloadFile(@RequestBody Map<String,Object> map) throws IOException {
  String path = map.get("path").toString();
  HttpHeaders headers = new HttpHeaders();
  headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
  headers.setContentDispositionFormData("attachment", path.substring(path.lastIndexOf("/") + 1));
  return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(new File(path)), headers, HttpStatus.CREATED);
}

第二種:這種方式用於文件在項目中

vue:

      download(){
        window.open(this.paths.baseURL+'risk/downloadRisk')
      },

java:

   @ApiOperation(notes = "下載",value = "下載")
    @GetMapping(value = "downloadRisk")
//    @RequiresPermissions("risk:download")
    public void downloadRisk(HttpServletResponse response) throws IOException {
        try {
            String path = System.getProperty("user.dir")+"\\trunk\\src\\main\\resources\\excelTemplate\\dowload\\風險辨識模板.doc";
            File file = new File(path);
            InputStream fis;
            fis = new BufferedInputStream(new FileInputStream(path));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            response.reset();
            String fileName = URLEncoder.encode("風險數據模板報告.doc","UTF-8");
            response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.addHeader("Content-Length", "" + file.length());
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

 


免責聲明!

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



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