前端代码

    /**
	 * 下载文件
	 */
	 download(id) {
	     this.$request({
	         url: '/file/download/' + id,
	         method: 'get',
	         //responseType 参数必不可少
	         responseType: 'blob'
	     }).then((response) => {
				//构造一个blob对象来处理数据
	             const blob = new Blob([response.data]);
	             //获取文件名称
	             let fileName = decodeURIComponent(response.headers['content-disposition'].split(';')[1].split('=')[1]);
	             fileName = fileName.substring(1, fileName.length - 1);
	             //对于<a>标签,只有 Firefox 和 Chrome(内核) 支持 download 属性
	             //IE10以上支持blob但是依然不支持download
	             //支持a标签download的浏览器
	             if ('download' in document.createElement('a')) {
	                 //创建a标签
	                 const link = document.createElement('a');
	                 //a标签添加属性
	                 link.download = fileName;
	                 link.style.display = 'none';
	                 link.href = URL.createObjectURL(blob);
	                 document.body.appendChild(link);
	                 //执行下载
	                 link.click();
	                 //释放url
	                 URL.revokeObjectURL(link.href);
	                 //释放标签
	                 document.body.removeChild(link);
	             } else { 
	             	 //其他浏览器
	                 navigator.msSaveBlob(blob, fileName);
	             }
	         }
	     );
	
	 },

后端代码

 /**
     * 下载文件
     */
    @GetMapping("/file/download/{id}")
    public ResponseEntity<InputStreamResource> download(@PathVariable Long id, HttpSession session) throws UnsupportedEncodingException, FileNotFoundException {
        FileResource fileResource = fileResourceService.findById(id);
        //获取需要下载的文件流对象
        FileInputStream fileInputStream = fileService.download(fileResource.getUri());
        //统计下载次数
        Long userId = (Long) session.getAttribute(Constant.USER_KEY);
        downService.save(new Down().setCreateTime(LocalDateTime.now()).setDownUserId(userId).setResourceId(id));
        //对文件名进行url编码处理防止出现乱码
        String newName = URLEncoder.encode(fileResource.getFileName() + fileResource.getUri().substring(fileResource.getUri().lastIndexOf(".")).toLowerCase(), "utf-8")
                .replaceAll("\\+", "%20").replaceAll("%28", "\\(")
                .replaceAll("%29", "\\)").replaceAll("%3B", ";")
                .replaceAll("%40", "@").replaceAll("%23", "\\#")
                .replaceAll("%26", "\\&").replaceAll("%2C", "\\,");
        HttpHeaders headers = new HttpHeaders();
        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
        headers.add("Content-Disposition", String.format("attachment; filename=\"%s\"", newName));
        headers.add("Expires", "0");
        headers.add("Pragma", "no-cache");
        return org.springframework.http.ResponseEntity
                .ok()
                .headers(headers)
                .contentLength(fileResource.getFileSize())
                .contentType(MediaType.parseMediaType("application/octet-stream"))
                .body(new InputStreamResource(fileInputStream));
    }
Logo

前往低代码交流专区

更多推荐