美文网首页
SpringBoot | Ajax | Vue前后端分离下载文件

SpringBoot | Ajax | Vue前后端分离下载文件

作者: nesanero | 来源:发表于2022-09-07 17:42 被阅读0次

    ● 后端: 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();
    }
    

    相关文章

      网友评论

          本文标题:SpringBoot | Ajax | Vue前后端分离下载文件

          本文链接:https://www.haomeiwen.com/subject/gdponrtx.html