【实用代码】SpringBoot | Ajax | Vue前后端分离下载文件的方式

图片[1]-【实用代码】SpringBoot | Ajax | Vue前后端分离下载文件的方式-南逸博客

 后端: SpringBoot

@ApiOperation(value = "下载附件")
@ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "附件 id", required = true),
})
@PostMapping(value = "/download/{id}", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
public ResponseEntity<ByteArrayResource> download(@PathVariable("id") String id, HttpServletRequest request) {
    // 返回类型 org.springframework.http.ResponseEntity
    try {
        User userByToken = getUserByToken(request);
        if (null == userByToken || null == userByToken.getId()) {
            return ResponseEntity.status(500).build();
        }
        return ResponseEntity.ok().contentType(MediaType.APPLICATION_OCTET_STREAM)
                .header("Content-Disposition", "attachment;filename=" + java.net.URLEncoder.encode(文件名, "UTF-8"))
                .body(new ByteArrayResource(文件字节数组));
    } catch (Exception e) {
        log.error("下载文件失败" + e);
        throw new RuntimeException("下载文件失败" + e);
    }
}

 前端: Vue

function download(){
  if (!this.$store.state.user?.token) {
    this.$message.error('您还未登录!');
    return;
  }
  const vueObj = this;
  const url = `请求地址 url`;
  const xhr = new XMLHttpRequest();
  xhr.open('POST', url, true);
  xhr.setRequestHeader('token', this.$store.state.user?.token);
  xhr.setRequestHeader('Content-Type', 'application/octet-stream');
  xhr.responseType = 'blob';
  // 请求的回调
  xhr.onload = function () {
    if (this.status === 200) {
        const reader = new FileReader();
        reader.readAsDataURL(this.response);
        reader.onload = function (e) {
            const a = document.createElement('a');
            a.download = '文件名';
            a.href = e.target.result;
            document.documentElement.appendChild(a);
            a.click();
            a.remove();
        };
    } else {
        vueObj.$message.error('您还未登录!');
    }
    };
  // 发送请求
  xhr.send();
}
© 版权声明
THE END
喜欢就支持一下吧
点赞13 分享
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

取消
昵称表情图片