[英]How to upload files to AWS S3 bucket from the react frontend
Hello I am trying to upload images from my react frontend but its unable to read the file in axios and the images are not being uploaded.您好,我正在尝试从我的 React 前端上传图片,但它无法读取 axios 中的文件,并且图片未上传。
This is my code.这是我的代码。
<form onSubmit={Upload}>
<input
type='file'
onChange={(e) => {
generate(e.target.files);
}}
/>
<button type='submit'>Submit</button>
</form>
const generate = async (data) => {
const payload = {
entity: 'test',
userId: '200',
documentFileName: data[0].name,
action: 'putObject',
};
console.log('DAATA', data[0].name);
await api
.generatePreSignedUrl(payload, token)
.then((res) => {
setUploadUrl(res.data.data);
setImageData(data);
})
.catch((err) => {
console.log('Error', err);
});
};
const Upload = async (e) => {
e.preventDefault();
console.log('IMAGEdata', imageData);
console.log('URL', uploadUrl);
let file = imageData[0];
console.log('THIS IS FILE', file);
console.log('FILENAME', file.name);
console.log('FIELETYPE', file.type);
var options = {
headers: {
'Content-Type': file.type,
},
};
await axios
.put(uploadUrl, file, options)
.then((res) => {
console.log('Response from s3');
console.log(res);
})
.catch((error) => {
alert('ERROR ' + JSON.stringify(error));
});
};
Here imageUrl is the signed URL that I get from was to upload my files.这里的 imageUrl 是我从中获得的签名 URL 是上传我的文件。 I am successfully able to call the put request to upload the file but the image or file is not being read and uploaded.
我能够成功调用放置请求来上传文件,但图像或文件未被读取和上传。
This is the response when I am trying to look at the uploaded file.这是我尝试查看上传文件时的响应。
This XML file does not appear to have any style information associated with it. The document tree is shown below.
<Error>
<Code>NoSuchKey</Code>
<Message>The specified key does not exist.</Message>
<Key>documents/ama/test/200/displaypicture.png</Key>
<RequestId>R7M63AHQKDNC6NH5</RequestId>
<HostId>3u8Jb8Ev4S1s/ODicL3Py4hvrvwKKOs/5zGxUEDYORfN1+U37Zx8PfYvIcGWUIAfeCqHpWqXd8o=</HostId>
</Error>
Look at the AWS SDK for JavaScript Developer Guide Version 3. There are examples that show how to upload photos to an Amazon S3 bucket.查看适用于 JavaScript 的 AWS 开发工具包开发人员指南版本 3。有一些示例展示了如何将照片上传到 Amazon S3 存储桶。
Uploading photos to Amazon S3 from a browser 从浏览器将照片上传到 Amazon S3
A pretty simple way to use this node module to achieve this: https://www.npmjs.com/package/react-aws-s3 https://medium.com/@steven_creates/uploading-files-to-s3-using-react-js-hooks-react-aws-s3-c4c0684f38b3 enter image description here使用此节点模块实现此目的的一种非常简单的方法: https ://www.npmjs.com/package/react-aws-s3 https://medium.com/@steven_creates/uploading-files-to-s3-using -react-js-hooks-react-aws-s3-c4c0684f38b3在此处输入图像描述
npm install --save react-aws-s3 npm install --save react-aws-s3
User " aws-sdk " and use this code
用户“aws-sdk”并使用此代码
import React ,{useState} from 'react';
import AWS from 'aws-sdk'
const S3_BUCKET ='YOUR_BUCKET_NAME_HERE';
const REGION ='YOUR_DESIRED_REGION_HERE';
AWS.config.update({
accessKeyId: 'YOUR_ACCESS_KEY_HERE',
secretAccessKey: 'YOUR_SECRET_ACCESS_KEY_HERE'
})
const myBucket = new AWS.S3({
params: { Bucket: S3_BUCKET},
region: REGION,
})
const UploadImageToS3WithNativeSdk = () => {
const [progress , setProgress] = useState(0);
const [selectedFile, setSelectedFile] = useState(null);
const handleFileInput = (e) => {
setSelectedFile(e.target.files[0]);
}
const uploadFile = (file) => {
const params = {
ACL: 'public-read',
Body: file,
Bucket: S3_BUCKET,
Key: file.name
};
myBucket.putObject(params)
.on('httpUploadProgress', (evt) => {
setProgress(Math.round((evt.loaded / evt.total) * 100))
})
.send((err) => {
if (err) console.log(err)
})
}
return <div>
<div>Native SDK File Upload Progress is {progress}%</div>
<input type="file" onChange={handleFileInput}/>
<button onClick={() => uploadFile(selectedFile)}> Upload to S3</button>
</div>
}
export default UploadImageToS3WithNativeSdk;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.