我正在尝试从角度上传文件。而且我还想显示上传进度。
upload.service.ts
public uploadProductImage(obj: FormData, id: string) {
return this._http.post(baseUrl + `/product/upload`, obj, {
headers: {
product_id: id,
},
reportProgress : true,
observe : 'events'
});
}
upload.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);
}
);
}
现在可以上传图片了。只有进度条不起作用。我立即收到一个事件,HttpEventType.UploadProgress
和event.loaded
和event.total
都相等。
因此进度条直接变为100
,但是要完成请求需要一些时间。
答案 0 :(得分:0)
我有同样的问题。对我来说,服务器位于localhost上,因此,上传是即时的,进度始终是100%。 尝试在Chrome浏览器中限制请求,然后在上传完成之前会看到其他进度百分比。
如何在Chrome中限制网络的步骤:
答案 1 :(得分:0)
我正在一个新项目中使用它。它正在工作。希望对您有帮助
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)
);
}