gpt4 book ai didi

angular - 如何从 Angular 将图像作为 blob 发送?

转载 作者:行者123 更新时间:2023-12-04 14:20:49 29 4
gpt4 key购买 nike

我正在使用文件输入标签来获取图像文件。现在,我想将它作为一个 blob 发送,我想将它作为字符串存储在数据库中。我将检索它并将其渲染为带有 get 调用的图像。

但是如何将图像发布为 blob?

最佳答案

您可以像这样上传文件:
TS

import { HttpClient } from "@angular/common/http";
import { Injectable } from "@angular/core";
import { Component, OnInit } from '@angular/core';



@Injectable({
providedIn: "root"
})
export class UploadService {

constructor(private httpClient: HttpClient) {
}


public uploadFile<T>(file: File): Observable<T> {
let formData = new FormData();
formData.append('file', file, file.name);

var request = this.httpClient
.post<T>(
"url/to/backend/upload",
formData
);
return request;

}

}


@Component({
selector: 'app-carga',
templateUrl: './carga.component.html',
template:
`
<input class="form-control" #fileInput type="file" [multiple]="false"/>
<button type="button" class="btn btn-outline-success"
(click)="uploadFile(fileInput)">Cargar</button>
`

})
export class CargaComponent implements OnInit {

constructor(public uploader: UploadService) {
}

ngOnInit(): void {
}
public uploadResult?: any;

async uploadFile(fileInput: any) {
let files: File[] = fileInput.files;
if (files.length < 1) {
return;
}

let file = files[0];
try {

this.uploader.uploadFile(file)
.subscribe(result => {
console.log(result);
fileInput.value = null;
},
error => {
console.error(error);
})

} catch (error) {

console.warn("File upload failed.");
console.error(error);

}
}

}

关于angular - 如何从 Angular 将图像作为 blob 发送?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55077393/

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