这里我有下面这样的动态数据
data = [
"https://dummyimage.com/200x200/000/fff.jpg&text=test",
"https://dummyimage.com/200x200/000/fff.jpg&text=testOne",
"https://dummyimage.com/200x200/000/fff.png&text=testTwo"
]
点击按钮我想从这些 url 中获取所有图像并将其保存为 zip
问题:当我能够以 zip 格式下载文件并尝试解压缩时,我收到错误消息,因为无法将 image.zip 作为 archieve 打开,如果我另存为单个图像,图像也无法打开并且存在任何方式来存储
下面是我的代码
downloadImageData(){
var blob = new Blob([this.data], { type: 'application/zip'' });
FileSaver.saveAs(blob,'image.zip');
}
这里我同时拥有 png 和 jpg 以及各种类型的数据,因此链接将获得的任何数据都必须下载为 zip 文件是否有任何用于 angular 5+ 的方法。我也在使用文件保存 Angular 包
JS ZIP _body resp
通过使用 http 模块 im 获取以下数据 [
{
"_body": {
},
"status": 200,
"ok": true,
"statusText": "OK",
"headers": {
"date": [
"Sun",
" 25 Nov 2018 12:18:47 GMT"
],
"cache-control": [
"public",
" max-age=43200"
],
"expires": [
"Mon",
" 26 Nov 2018 00:18:47 GMT"
],
"content-disposition": [
"attachment; filename=2B.JPG"
],
"content-length": [
"40649"
],
"server": [
"Werkzeug/0.14.1 Python/2.7.13"
],
"content-type": [
"image/jpg"
]
},
"type": 2,
"url": "http://some url"
}
]
最佳答案
我已经创建了一个演示应用程序 here .
P.S:该代码仅供引用,可能不包含标准编码实践,但可能会指导您创建自己的解决方案版本。
我正在使用 jszip压缩文件。
app.module.ts:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';
import { AppComponent } from './app.component';
import * as JSZip from 'jszip';
import { saveAs } from 'file-saver';
@NgModule({
imports: [ BrowserModule, HttpClientModule ],
declarations: [ AppComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule { }
app.component.ts:
import { OnInit, Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import * as JSZip from 'jszip';
import { saveAs } from 'file-saver';
@Component({
selector: 'my-app',
template: `<button (click)='downloadZip()'>Download</button>`
})
export class AppComponent {
constructor(private http: HttpClient) {
}
downloadZip() {
this.loadSvgData("https://c.staticblitz.com/assets/client/icons/file-icons/angular-component-31179578a9a8a16512e9e90ade26549a.svg",
this.saveAsZip);
}
private loadSvgData(url: string, callback: Function) : void{
this.http.get(url, { responseType: "arraybuffer" })
.subscribe(x => callback(x));
}
private saveAsZip(content: Blob) : void{
var zip = new JSZip.default();
zip.file("image.svg", content);
zip.generateAsync({ type: "blob" })
.then(blob => saveAs(blob,'image.zip'));
};
}
解释:
该应用程序只有一个按钮,单击该按钮将使用 HttpClient
从服务器下载图像文件。它将使用 jszip
压缩下载的数据,并使用 file-saver
将其保存到浏览器。
希望对您有所帮助!
关于javascript - 无法使用 Angular 6将图像下载为zip文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53397818/