Max*_*ark 5 file-upload typescript angular
我正在尝试从 angular 上传文件。我也想显示上传进度。
上传服务.ts
public uploadProductImage(obj: FormData, id: string) {
return this._http.post(baseUrl + `/product/upload`, obj, {
headers: {
product_id: id,
},
reportProgress : true,
observe : 'events'
});
}
Run Code Online (Sandbox Code Playgroud)
上传.component.ts
uploadClick() {
const fd = new FormData();
// for(const f of this.file_url) {
// fd.append('image', f.file, f.file.name);
// }
fd.append('image', this.file_url[0].file, this.file_url[0].file.name);
this.service.uploadProductImage(fd, this.product_id.toString())
.subscribe(
event => {
if (event.type === HttpEventType.UploadProgress) {
console.log(event.loaded, event.total);
this.progress = Math.round(event.loaded / event.total * 100);
} else if (event.type === HttpEventType.Response) {
console.log(event.body);
this.file_url = [];
}
},
err => {
console.log(err);
}
);
}
Run Code Online (Sandbox Code Playgroud)
现在图像上传正在工作。只有进度条不起作用。我HttpEventType.UploadProgress立即收到一个事件,event.loaded并且event.total两者都是平等的。
所以progressbar 直接变成了100但是完成请求需要一些时间。
我遇到过同样的问题。对我来说,服务器在本地主机上,因此上传是即时的,进度总是 100%。尝试在 Chrome 中限制请求,您将在上传完成之前看到其他一些进度百分比。
如何在 Chrome 中限制网络的步骤:
我正在一个新项目中使用这个。它正在发挥作用。希望它能帮助你
import { HttpRequest, HttpEventType, HttpResponse } from '@angular/common/http';
uploadMethod() {
const formData: FormData = new FormData();
formData.append('file', this.selectedFile);
const req = new HttpRequest('POST', apiEndpoint, formData, {
reportProgress: true,
});
this.http.request(req)
.subscribe(
(event) => {
if (event.type === HttpEventType.UploadProgress) {
// This is an upload progress event. Compute and show the % done:
this.percentDone = Math.round(100 * event.loaded / event.total);
console.log(`File is ${this.percentDone}% uploaded.`);
} else if (event instanceof HttpResponse) {
console.log('File is completely uploaded!');
console.log(event.body);
}
},
err => console.error(err)
);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1751 次 |
| 最近记录: |