Vue 下载文件方式总结

第一种方式:使用 window.location.href

限于使用get方式

downloadRest(scope){
           this.$axios({
          method:'post',
          url:'/api/upload/file/preview',
          data:{"filePath":scope.row.filePath},
          headers:{
            'Content-Type':'application/json;charset=utf-8'      //改这里就好了
          }
        }).then(res => {
            // 文件下载方式二
             //window.open(res.data.datas.fileUrl)
             // 文件下载方式一
             window.location.href =res.data.datas.fileUrl
         
        })
          .catch(function (error) {
            console.log(error)
          })
        
      },

对应SpringBoot 后台业务逻辑代码片段

/**
	 * 查询指定文件的预览地址
	 * 
	 * @param file
	 */
	@ApiOperation(httpMethod = "POST", value = "查询指定文件的预览地址")
	@RequestMapping(value = "/preview", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	public Result preview(@RequestBody Map<String, Object> parame) {
		String filePath = String.valueOf(parame.get("filePath"));
		MinioUploadEntity entity = new MinioUploadEntity("http://192.168.1.74:9000", "minioadmin", "minioadmin");
		MinioUploadUtil util = new MinioUploadUtil(entity);
		String fileUrl = null;
		try {
			fileUrl = util.getPreviewAddress(filePath, "gxpt-img");
		} catch (InvalidKeyException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return Result.error("文件预览地址获取失败");
		} catch (ErrorResponseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return Result.error("文件预览地址获取失败");
		} catch (InsufficientDataException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return Result.error("文件预览地址获取失败");
		} catch (InternalException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return Result.error("文件预览地址获取失败");
		} catch (InvalidResponseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return Result.error("文件预览地址获取失败");
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return Result.error("文件预览地址获取失败");
		} catch (XmlParserException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return Result.error("文件预览地址获取失败");
		} catch (ServerException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return Result.error("文件预览地址获取失败");
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return Result.error("文件预览地址获取失败");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return Result.error("文件预览地址获取失败");
		}
		return Result.ok().setData("fileUrl", fileUrl);
	}

 

第二种方式:如果后端直接给出了文件在服务器中的地址,可以直接使用a标签或window.open

​
downloadRest(scope){
           this.$axios({
          method:'post',
          url:'/api/upload/file/preview',
          data:{"filePath":scope.row.filePath},
          headers:{
            'Content-Type':'application/json;charset=utf-8'      //改这里就好了
          }
        }).then(res => {
            // 文件下载方式二
             //window.open(res.data.datas.fileUrl)
             // 文件下载方式一
             window.location.href =res.data.datas.fileUrl
         
        })
          .catch(function (error) {
            console.log(error)
          })
        
      },

​

对应SpringBoot 后台逻辑代码

/**
	 * 查询指定文件的预览地址
	 * 
	 * @param file
	 */
	@ApiOperation(httpMethod = "POST", value = "查询指定文件的预览地址")
	@RequestMapping(value = "/preview", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	public Result preview(@RequestBody Map<String, Object> parame) {
		String filePath = String.valueOf(parame.get("filePath"));
		MinioUploadEntity entity = new MinioUploadEntity("http://192.168.1.74:9000", "minioadmin", "minioadmin");
		MinioUploadUtil util = new MinioUploadUtil(entity);
		String fileUrl = null;
		try {
			fileUrl = util.getPreviewAddress(filePath, "gxpt-img");
		} catch (InvalidKeyException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return Result.error("文件预览地址获取失败");
		} catch (ErrorResponseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return Result.error("文件预览地址获取失败");
		} catch (InsufficientDataException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return Result.error("文件预览地址获取失败");
		} catch (InternalException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return Result.error("文件预览地址获取失败");
		} catch (InvalidResponseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return Result.error("文件预览地址获取失败");
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return Result.error("文件预览地址获取失败");
		} catch (XmlParserException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return Result.error("文件预览地址获取失败");
		} catch (ServerException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return Result.error("文件预览地址获取失败");
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return Result.error("文件预览地址获取失败");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return Result.error("文件预览地址获取失败");
		}
		return Result.ok().setData("fileUrl", fileUrl);
	}

 

第三种方式:使用blob类型

download(scope){
      // 通过blob 下载文件方法暂时未调试成功
          this.$axios.get('/api/upload/file/fileDownload?filePath=' +scope.row.filePath).then(function(response){   
     if (!response.data) {
        this.$Message.error('下载内容为空')
        return
      }
      const disposition = response.headers['content-disposition'];
      let fileName = disposition.substring(disposition.indexOf('filename=') + 9, disposition.length);

      let url = window.URL.createObjectURL(new Blob([response.data]), {
type: "image/jpeg"
})
      let link = document.createElement('a')
      link.style.display = 'none'
      link.href = url
      link.setAttribute('download', fileName)
        
      document.body.appendChild(link)
      link.click()
      //释放URL对象所占资源
      window.URL.revokeObjectURL(url)
      //用完即删
      document.body.removeChild(link)
}).catch(function (response){
	console.log(response);//发生错误时执行的代码
});
      }

对应SpringBoot 后台逻辑代码片段

/**
	 * 文件下载
	 *
	 */
	@ApiOperation(httpMethod = "GET", value = "下载指定文件")
	@RequestMapping(value = "/fileDownload", method = RequestMethod.GET)
	public void fileDownload(HttpServletRequest request, HttpServletResponse response) {
		String filePath = request.getParameter("filePath");
		MinioUploadEntity entity = new MinioUploadEntity("http://192.168.1.74:9000", "minioadmin", "minioadmin");
		MinioUploadUtil util = new MinioUploadUtil(entity);
		GetObjectResponse fis = null;	
		try {
		
			fis = util.downloadFile(filePath, "gxpt-img");
//          输出Minio 文件头信息
//			Headers headers = fis.headers();
//			Iterator<Pair<String, String>>  iterators = headers.iterator();
//			iterators.forEachRemaining(obj -> {
//				response.setHeader(obj.getFirst(), obj.getSecond());
//			});
			
			response.setHeader("Content-Disposition", "attachment; filename=" + filePath);
			response.setContentType("image/jpeg");
			IOUtils.copy(fis, response.getOutputStream());
			response.flushBuffer();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (fis != null) {
				try {
					fis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

	}

MINI 类型

  • 1
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值