javascript - 在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);
}
}
解决方案
推荐阅读
- c++ - 使用优先级队列的 K 排序数组 - C++
- java - 无法从 Java 类获取自定义注解
- java - 从外部 URL 获取 thymeleaf 片段
- android - 将环境设置为 ExternalStorageDirectory 时,无法在 android 上使用 java 创建目录文件
- python - 直接从 Flask 服务上传到 Minio
- java - RestAssured - 如何从 json 响应中读取数组元素
- mysql - FDQuery和OnCalcFields,获取上一行
- java - 如何检查哪个线程当前正在锁定静态变量
- python-2.7 - 目录和文件的 Python 递归到 5 个级别
- java - 如何通过单击另一个类的按钮来执行该方法?