第 1 部分. 通过 FormData 将文件上传到 API
在您的服务文件中,例如upload.service.ts
您需要创建通过 POST 方法上传文件的功能。下面是这个函数的一个例子:
getUploadHeaders() {
let headers = new Headers({'Accept': 'application/json'});
headers.delete('Content-Type');
return headers;
}
addNewPost(newPost: FormData): Observable<FormData> {
const endpoint = 'https://yourApiUrl.com';
return this.http
.post(endpoint, newPost, { headers: this.getUploadHeaders() })
.catch((e) => this.handleError(e));
}
现在您应该在组件中创建上传功能,例如upload.component.ts
。这是使用 FormData 进行上传功能的示例。
fileToUpload: File = null;
constructor(private uploadService: UploadService) { }
handleFileInput(files: FileList) {
this.fileToUpload = files.item(0);
}
saveFileToApi() {
const saveForm: FormData = new FormData();
if (this.fileToUpload) {
// if you need/want to append other fields to API endpoint
saveForm.append('name', this.name);
saveForm.append('link', this.link);
saveForm.append('description', this.description);
// if you have to append number
saveForm.append('age', this.age.toString());
// append image
saveForm.append('fileFieldNameOnYourApi', this.fileToUpload, this.fileToUpload.name);
}
this.uploadService.addNewPost(saveForm).subscribe(() => {
console.log('Upload success!');
}, error => {
console.log('Upload failed!');
});
}
In saveFileToApi
- 您还可以附加表单的其他字段。请注意,您应该将数字字段转换为字符串。Here https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects您可以阅读有关 FormData 对象用法的更多信息。
要通过 FormData 上传文件,您需要 3 个参数:API 端点上的 propertyName、文件和该文件的名称。
而在你的upload.component.html
你需要有这样的形式:
<form (ngSubmit)="onSubmit()">
<label for="fileField">Chose file to upload</label>
<input type="file"
id="fileField"
name="fileField"
(change)="handleFileInput($event.target.files)">
<button type="submit">Speichern</button>
</form>
有关 FormData 的更多详细信息,请阅读this https://developer.mozilla.org/en-US/docs/Web/API/FormData有关 FormData.append() 的更多信息,请阅读this https://developer.mozilla.org/en-US/docs/Web/API/FormData/append.
第2部分.从API获取上传的图像
你应该设置responseType: ResponseContentType.Blob
在您的 GET-Request 设置中,因为这样您就可以将图像获取为 blob,并稍后将其转换为 base64 编码的源。你上面的代码不好。如果您想正确执行此操作,请创建单独的服务以从 API 获取图像。因为在组件中调用HTTP-Request是不好的。
这是一个工作示例:
Create image.service.ts
or use upload.service.ts
从第 1 部分开始(也许您可以为该服务指定另一个名称)并输入以下代码:
getImage(imageUrl: string): Observable<File> {
return this.http
.get(imageUrl, { responseType: ResponseContentType.Blob })
.map((res: Response) => res.blob());
}
现在您需要在您的中创建一些函数image.component.ts
获取图像并以 html 形式显示。
要从 Blob 创建图像,您需要使用 JavaScriptFileReader
。
这是创建新的函数FileReader
并监听 FileReader 的 load-Event。结果,该函数返回 base64 编码的图像,您可以在 img src-attribute 中使用它:
imageToShow: any;
createImageFromBlob(image: Blob) {
let reader = new FileReader();
reader.addEventListener("load", () => {
this.imageToShow = reader.result;
}, false);
if (image) {
reader.readAsDataURL(image);
}
}
现在你应该使用你创建的ImageService
从 api 获取图像。您应该订阅数据并将该数据提供给createImageFromBlob
-功能。这是一个示例函数:
getImageFromService() {
this.isImageLoading = true;
this.imageService.getImage(yourImageUrl).subscribe(data => {
this.createImageFromBlob(data);
this.isImageLoading = false;
}, error => {
this.isImageLoading = false;
console.log(error);
});
}
现在您可以使用您的imageToShow
- HTML 模板中的变量如下所示:
<img [src]="imageToShow"
alt="Place image title"
*ngIf="!isImageLoading; else noImageFound">
<ng-template #noImageFound>
<img src="fallbackImage.png" alt="Fallbackimage">
</ng-template>
我希望这个描述很容易理解,并且您可以在您的项目中使用它。