首页 > 解决方案 > 在javascript中处理Arraybuffer的正确方法是什么?

问题描述

我正在尝试从带有 Reactjs UI 的 springboot 应用程序下载 .exe。

我遇到的问题是,下载 blob 时下载不会立即显示进度。仅在 blob 完全下载后才开始下载,并直接显示为下载完成。直接在 URL 中使用 API 调用可以正常工作,但是使用 Axios 调用,我遇到了这个问题。我应该以不同的方式处理 javascript 的响应吗?

这是我的后端代码:

private static final ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
private static final Resource resource = resolver.getResource("abc/ABC.exe");
public ResponseEntity<ByteArrayResource> clientSetup() {
        try {
            byte[] templateContent = org.springframework.util.FileCopyUtils.copyToByteArray(resource.getInputStream());
            ByteArrayResource inputStream = new ByteArrayResource(templateContent);

            if(inputStream.exists()) {

                return ResponseEntity.ok()
                        .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + "ABC.exe"+ "\"")
                        .contentLength(inputStream.contentLength())
                        .contentType(MediaType.parseMediaType("application/octet-stream"))
                        .body(inputStream);

            }else {
                throw new Exception();
            }
        }catch(Exception e) {
            logger.error(e.getMessage());
            e.printStackTrace();
            return new ResponseEntity<ByteArrayResource >(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

用户界面:

  try {
    const response = yield axios.get("/download/abc", {

      responseType: "arraybuffer"
    });
    let blob = new Blob([response.data], {
      type: response.headers["content-type"]
    });
    let downloadUrl = window.URL.createObjectURL(blob),
      filename = "",
      disposition = response.headers["content-disposition"];

    if (disposition && disposition.indexOf("attachment") !== -1) {
      let filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/,
        matches = filenameRegex.exec(disposition);

      if (matches != null && matches[1]) {
        filename = matches[1].replace(/['"]/g, "");
      }
    }

    let a = document.createElement("a");
    if (typeof a.download === "undefined") {
      window.location.href = downloadUrl;
    } else {
      a.href = downloadUrl;
      a.download = filename;
      document.body.appendChild(a);
      a.click();
    }
  } catch (error) {
    console.log(error);
  }
}

标签: javascriptjavareactjsspring-bootaxios

解决方案


推荐阅读