gpt4 book ai didi

angularjs - 使用 AngularJS 从服务器下载并保存文件

转载 作者:行者123 更新时间:2023-12-02 23:27:43 26 4
gpt4 key购买 nike

我遇到了以下问题,但找不到解决方案。我使用 Spring Boot 创建了端点,当我使用 Postman 时我收到了有关正文请求的图片的回复。

但是当我尝试使用 Angular、Blob 和 FileSaver 在计算机上下载并保存文件时,我保存的文件无法读取。

这是我的 Angular Controller :

vm.download = function (filename) {
console.log("Start download. File name:", filename);
$http.get('api/files/download/' + filename)
.then(function (response) {
console.log(data);
var data = new Blob([response.data], {type: 'image/jpeg;charset=UTF-8'});
FileSaver.saveAs(data, filename);
})
}

这是我的端点:

@RequestMapping(value = "/files/download/{id:.*}", method = RequestMethod.GET)
@ResponseBody
@Timed
public void DownloadFiles(@PathVariable String id, HttpServletRequest request, HttpServletResponse response) throws IOException {

MongoClient mongoClient = new MongoClient();
DB mongoDB = mongoClient.getDB("angularspingproject");


BasicDBObject query = new BasicDBObject();
query.put("filename", id);

GridFS fileStore = new GridFS(mongoDB, "fs");
GridFSDBFile gridFSDBFile = fileStore.findOne(query);

if (gridFSDBFile != null && id.equalsIgnoreCase((String) gridFSDBFile.getFilename())) {
try {
response.setContentType(gridFSDBFile.getContentType());
response.setContentLength((new Long(gridFSDBFile.getLength()).intValue()));
response.setHeader("content-Disposition", "attachment; filename=" + gridFSDBFile.getFilename());

IOUtils.copyLarge(gridFSDBFile.getInputStream(), response.getOutputStream());
} catch (IOException e) {
throw new RuntimeException("IOError writting file to output stream");
}
}
}

我的标题:

Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Content-Length: 316707
Content-Type: image/jpeg;charset=UTF-8
Pragma: no-cache
Server:Apache-Coyote/1.1
X-Application-Context : angularspingproject:8080
X-Content-Type-Options : nosniff
X-XSS-Protection: 1; mode=block
content-Disposition: attachment; filename=main_page.jpg

@编辑问题已解决

    vm.download = function (filename) {
$http.get('api/files/download/' + filename, {responseType:'blob'})
.then(function (response) {
console.log(response);
var data = new Blob([response.data], {type: 'image/jpeg;charset=UTF-8'});
FileSaver.saveAs(data, filename);
})
}

我将responseType: 'blob' 添加到$http

最佳答案

我猜你没有从 $http.get 调用中返回字节数组。尝试添加:

vm.download = function (filename) {
var config = {headers: {
'Accept': "image/jpeg"
}
};
$http.get('api/files/download/' + filename, config).then(function (response) {
var myBuffer= new Uint8Array( response.data );

var data = new Blob([myBuffer], {type: 'image/jpeg;charset=UTF-8'});
FileSaver.saveAs(data, filename);
})
}

关于angularjs - 使用 AngularJS 从服务器下载并保存文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37572528/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com