vue axios get和post请求下载文件,后台springmvc完整代码

 注意请求时要设置responseType,不加会中文乱码,被这个坑困扰了大半天。。。
axios post请求:
    download(index,row){
        var ts = this;
        axios.post(this.paths.baseURL+'file/downloadFile',
        {path:row.zurl},
        {responseType: 'blob'}
        ).then(msg => {
          console.log(msg.data)
          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('下载文件失败')
        })
      }

 

后台接口:

    @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);
}

axios get请求下载
        axios.get(this.paths.baseURL+'risk/excelRisk',
        {responseType: 'blob'}
        ).then((msg) => {
          console.log(msg)
              let url = window.URL.createObjectURL(new Blob([msg.data]));
              let link = document.createElement('a')
              link.style.display = 'none'
              link.href = url
              link.setAttribute('download', '未评估风险数据.xls')
              document.body.appendChild(link)
              link.click()              
          }).catch((error) => {
            console.log(error)
              this.$message({
                type:'error',
                message:'服务器异常'                 
              })
          })
    @GetMapping(value = "excelRisk",produces = {"application/octet-stream;charset=utf-8"})
    //@RequiresRoles("risk:list")
    public void excelRisk(HttpServletResponse response) {
        try {
            Map<String,Object> map = new HashMap<String,Object>();
            Workbook workbook = RiskExcel.wpgRisk(riskService.excelRisk(map),"excelTemplate/risk_1.xlsx");
            OutputStream out=response.getOutputStream();
            response.setHeader("Content-Type","application/vnd.ms-excel");
            response.addHeader("Content-Disposition","attachment;filename=为评估数据.xmls");
            response.setContentType("application/octet-stream");
            response.setCharacterEncoding("UTF-8");
            workbook.write(out);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

 

 

 
posted @ 2020-04-08 16:38  _Lawrence  阅读(2313)  评论(0编辑  收藏  举报