我正在创建一个web应用程序,前端使用React / Aws Amplify,后端使用AWS API-Gateway和S3,用户身份验证使用Cognito。我有一个页面,用户需要提交一个表单和一个文件。我可以将其设置为文本文件,但一旦我开始处理二进制文件,就发生了不好的事情。
我在AWS中构建了API,并使用Postman和Curl对其进行了测试,我能够发布二进制文件。当我通过Amplify进行调用时,它停止工作。我可以通过Axios进行调用,但是我需要关闭身份验证,因此我尝试通过amplify来完成此操作。我也不想使用amplify存储,因为它不能满足我的需求。通常发生的情况是文件大小比发送的文件大,当我从S3下载它时,它不再工作。
import React, { Component } from "react";
import "./Dashboard.css";
import { API } from "aws-amplify";
import { saveAs } from 'file-saver';
import axios from 'axios';
export default class Home extends Component {
uploadLambda = async (event) => {
//This one work if I turn off User Authentication
let file = event.target.files[0];
let reader = new FileReader();
reader.readAsArrayBuffer(file);
reader.onload = async () => {
try
{
return axios({
method: 'POST',
url: 'https://XXXXXXXXXX.execute-api.us-east-1.amazonaws.com/dev/upload',
headers: {
'Content-Type': 'application/pdf'
},
data: reader.result
});
}
catch(e)
{
console.log(e);
}
}
}
uploadImageLambda = async(event) => {
//This is the one I'm trying to get to work with binary files
var file_name = event.target.files[0].name;
console.log('Saving File Via Lambda: ' + file_name);
var reader = new FileReader();
reader.readAsDataURL(event.target.files[0]);
//reader.readAsBinaryString(event.target.files[0]);
//reader.readAsArrayBuffer(event.target.files[0]);
reader.onload = async () =>
{
try
{
/**
Someone suggested this but it does not fix the problem
let encoded = reader.result.toString().replace(/^data:(.*,)?/, '');
if ((encoded.length % 4) > 0) {
encoded += '='.repeat(4 - (encoded.length % 4));
}
console.log(encoded);
//"isBase64Encoded": "true",
**/
return await API.post("lambdadocshell", 'upload', { 'headers': { 'Content-Type': 'application/pdf', }, 'body': reader.result });
}
catch (e)
{
console.log(e);
}
}
}
render() {
return (
<div className="FileTest">
<h1>Upload A File</h1>
<form onSubmit={this.handleSubmit} enctype="multipart/form-data">
Select File: <input type="file" onChange={this.uploadLambda} />
</form>
</div>
);
}
}在上面的代码中,您可以看到两个上传函数,它们都命中相同的API-Gateway。uploadLambda只有在关闭了API-Gateway上的身份验证后才能工作。无论身份验证如何,uploadImageLambda都不起作用。我们确实在许多其他页面中使用了Amplify来将JSON来回移动到API,而没有出现问题。您还可以看到注释代码,因为我们尝试了许多不同的方法来使amplify工作。
发布于 2019-09-17 01:10:21
在与亚马逊网络服务支持人员交谈后,他们表示,amplify显然会对数据执行JSON.stringify操作,从而增加文件的长度。目前似乎没有解决此问题的方法。因此,他们建议我使用Axios向API Gateway发出请求。希望这个问题能在未来得到解决。
https://stackoverflow.com/questions/57855644
复制相似问题