【发布时间】:2019-09-09 14:04:52
【问题描述】:
我正在创建一个 Web 应用程序,使用 React / Aws Amplify 作为前端,AWS API-Gateway 和 S3 在后端,Cognito 作为我们的用户身份验证。我有一个页面,用户需要在其中提交表单和文件。我能够为文本文件设置它,但是一旦我开始处理二进制文件,就会发生不好的事情。
我在 AWS 中构建了 API,并使用 Postman 和 Curl 对其进行了测试,并且我能够发布二进制文件。当我通过 Amplify 拨打电话时,它停止工作。我可以通过 Axios 拨打电话,但我需要关闭身份验证,因此我尝试通过放大来执行此操作。我也不想使用放大存储,因为它不能满足我的需求。通常发生的情况是文件大小大于发送的文件,当我从 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>
);
}
}
在上面的代码中,您可以看到 2 个上传函数,它们都使用相同的 API-Gateway。 uploadLambda 有效,但前提是 API-Gateway 上的身份验证已关闭。无论身份验证如何,uploadImageLambda 都不起作用。我们确实在许多其他页面中使用 Amplify 将 JSON 来回移动到 API,而不会出现问题。您还可以查看注释代码,因为我们尝试了多种不同的方法来让放大工作。
【问题讨论】:
标签: react-native aws-lambda aws-api-gateway aws-amplify