[英]Can't upload image using Angular's HttpClient
I am able to upload an image perfectly fine using the native fetch POST:我可以使用本机获取 POST 完美地上传图像:
let formData = new FormData();
formData.append('file', event.target.files[0]);
console.log(event.target.files[0]);
fetch('http://localhost:8080/file/upload', {
method: 'POST',
headers:{
'Authorization': 'Bearer ' + JWT
},
body:formData
}).then(response => console.log(response));
However, when I try this using Angular's HttpClient, the request fails since the 'Content-Type': 'multipart/form-data' is not added.但是,当我使用 Angular 的 HttpClient 尝试此操作时,请求失败,因为未添加 'Content-Type': 'multipart/form-data'。
My Angular code:我的角度代码:
The file where I'm calling the service:我在其中调用服务的文件:
this.fileSaverService.uploadImage(event.target.files[0]).subscribe(
(data)=>{
console.log(data);
},
(error) => {
console.log(error);
}
);
The fileSaverService:文件保护服务:
uploadImage(fileToUpload) {
const endpoint = 'http://localhost:8080/file/upload';
const formData: FormData = new FormData();
formData.append('file', fileToUpload);
return this.api
.post(endpoint, formData, { headers: {'Content-Type': 'multipart/form-data'} });
}
The this.api: this.api:
post(endpoint: string, body: any, reqOpts: any = {}) {
reqOpts.headers = this.handleHeaders(reqOpts.headers);
return this.http.post(endpoint, JSON.stringify(body), reqOpts);
}
If I add the header manually when using HttpClient, I get this header without the boundary:如果我在使用 HttpClient 时手动添加标头,我会得到这个没有边界的标头:
However the native fetch adds this header automatically with the boundary if I don't specify a header and this works perfectly:但是,如果我不指定标头,则本机提取会自动将此标头与边界一起添加,这非常有效:
What are my options here?我在这里有哪些选择?
There are two problems with the code in your question:您问题中的代码有两个问题:
Content-Type
to multipart/form-data
yourself , the serialisation of your FormData
will not result in the correct header with boundaries being set behind the scenes.Content-Type
来multipart/form-data
自己,你的序列化FormData
不会导致与边界是幕后一套正确的标题。post
function, you have JSON.stringify(body)
, which is converting your FormData
object into a JSON string.post
函数中,您有JSON.stringify(body)
,它将您的FormData
对象转换为 JSON 字符串。 After doing this, you're simply attempting to POST a string rather than a complete FormData object.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.