我正在尝试使用 RestAPI 并传递令牌在 Azure blob 存储上上传图像。它适用于邮递员。我能够正确获取上传的图像。从 Angular 上传也可以,但是当我尝试获取上传的内容时,我得到一些文本而不是图像。以下是文本示例。 以下文字是我收到的全文的一部分。
------WebKitFormBoundaryCCltz7yE7w2qTIUX 内容配置:表单数据;名称=“文件”; filename="img3 - Copy - Copy.jpg" 内容类型:image/jpeg ����JFIF���ICC_PROFILE�0mntrRGB XYZ acsp���- desc�$rXYZgXYZ(bXYZ<�wtptPrTRCd(gTRCd(bTRCd(cprt�No᧟Js=٠+3Y��n���:�^�H @O����:�^�HJ�������vh %Y�����o|�@'7��ό�I��w�o��x���R��gx���}`)��f�n����R��vh*��w���No᧟f�hRr������:�p�U'+]��No᧟���y�)Y�������h�9��� /��/���)��o|�@*����)Y��� �r��@�����_?O ���o|�@2S����g/_�%9^�� ?��i��R��gx��Y����Vf�4��{�@,�� �gx�9z� I��w�XJs=٠���y�:�^�H @O���y�U'+]�J�����+��Js=٠+3Y� �Nf�4���K���Vf�4��k�� Vf�4|���O>0�W��u|�>� )3w��Y� �� /���Y^������)9Z�� �����S���%Y^�� ��r��@'7��ό)YZ������ ��?
我用来上传图片的代码
uploadFile(file: any, securedUrl: string){
this.securedUrl = securedUrl;
let reader = new FileReader();
reader.onload = (e: any) => {
const formData: FormData = new FormData();
formData.append('file', file);
formData.append('fileName', "file123");
var requestData = new Uint8Array(e.target.result);
const httpOptions = {
headers: new HttpHeaders({
'x-ms-blob-type': 'BlockBlob',
})
};
this.http.put(securedUrl, formData, httpOptions).subscribe(response => {
console.log(response);
});
};
reader.readAsArrayBuffer(file);
}
出现此错误的原因是 Azure 存储不支持
multipart/form-data
。您要做的是将图像文件的内容作为二进制数据读取并直接上传。
您的代码将类似于(未经测试的代码):
uploadFile(file: any, securedUrl: string){
this.securedUrl = securedUrl;
let reader = new FileReader();
reader.onload = (e: any) => {
var requestData = new Uint8Array(e.target.result);
const httpOptions = {
headers: new HttpHeaders({
'x-ms-blob-type': 'BlockBlob',
})
};
this.http.put(securedUrl, requestData, httpOptions).subscribe(response => {
console.log(response);
});
};
reader.readAsArrayBuffer(file);
}
下面是根据 Gaurav 的建议更新的代码。第二个参数(formData)被替换为选择上传的二进制文件。
uploadFile(file: any, securedUrl: string){
this.securedUrl = securedUrl;
let reader = new FileReader();
reader.onload = (e: any) => {
const httpOptions = {
headers: new HttpHeaders({
'x-ms-blob-type': 'BlockBlob',
})
};
this.http.put(securedUrl, file, httpOptions).subscribe(response => {
console.log(response);
});
};
reader.readAsArrayBuffer(file);
}