我需要从Angular向AWS API网关执行签名的POST请求,并发送包含文档和其他参数的multipart / form-data。
我创建如下的FormData:
const formData = new FormData();
formData.append('document', document, document.name);
formData.append('document_metadata', new Blob(
[JSON.stringify(metaData)],
{
type: 'application/json'
})
);
现在,要向AWS Gateway发出请求,我需要对请求进行签名,并将所有属性作为正文发送,这意味着我需要以某种方式将FormData传递给签名。问题在于,如果不对FormData的值进行流处理,就无法获取它们。
为此,我使用了Get HTTP Body of Form in JavaScript这里提到的方法。因此,我对文件进行流处理,将其值解码并合并。这给了我将与请求一起发送的字符串,并可以使用它来对请求签名(借助https://github.com/mar753/aws-signature-v4)。
async getFormDataStream(formData: FormData) {
const response = new Response(formData);
const stream = response.body;
const reader = stream.getReader();
const decoder = new TextDecoder('utf-8');
const parent = this;
let tempData = '';
const headers: Headers = response.headers;
headers.forEach((value, key) => {
if(key ==='content-type') {
this.customContentType = value;
}
});
await reader.read()
.then(function processData(result) {
tempData = tempData + decoder.decode(result.value);
if (result.done) {
parent.customFormData = tempData;
console.log('stream done');
return;
}
return reader.read().then(processData);
})
.catch((err) => {
console.log('catch stream cancellation:', err);
});
}
现在,我创建标题并请求:
const headers = {
headers: new HttpHeaders({
'X-Amz-Date': signature['X-Amz-Date'],
'X-Amz-Security-Token': user.sessionToken,
'x-api-access-token': user.getJwtToken(),
'x-api-id-token': user.getJwtToken(),
'Content-Type': this.customContentType, // contentType with boundary is generated from stream
authorization: signature.Authorization
};
this.http.post(APIGatewayEndpoint, this.customFormData, header); // customFormData is generated with stream
到目前为止,我所做的所有工作都可以正常通过,并且没有任何问题地通过授权并保存文件。但是问题是,除了.txt文件之外,所有其他文件都损坏了,我无法打开它。 我不得不猜测可能是什么问题:
关于上述内容的任何帮助将不胜感激,因为我目前无法选择。