简体   繁体   English

如何从 React 前端将文件上传到 AWS S3 存储桶

[英]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.

相关问题 如何在React JS中从S3存储桶中获取5个最新文件? - How to get 5 latest files from s3 bucket in react js? 如何转换从 S3 存储桶检索的流以将其用作 React 前端中的 jpeg 图像? - How do I convert a stream retrieved from S3 bucket to use it as jpeg image in my React frontend? 如何使用 React 和使用 aws-sdk 预签名的 axios 将文件上传到 S3 存储桶? - How to upload a file to S3 bucket with axios using React and a presigned using aws-sdk? 将视频文件上传到 S3 存储桶 (React js) - Upload video files into S3 bucket (React js) 如何从动态 HTML 生成 PDF 并将其上传到 AWS S3 存储桶而不下载 pdf? - How to generate PDF from dynamic HTML and upload it to AWS S3 bucket without download pdf? 来自 AWS S3 存储桶的图像在 React App 中旋转 - Images from an AWS S3 bucket being rotated in React App 如何将您的网站列入白名单以便能够查看 AWS S3 存储桶中的文件? - How to whitelist your website to be able to view files from AWS S3 bucket? 如何从 aws s3 存储桶下载所有图像(.jpg)文件 - How to Download all images(.jpg) files from a aws s3 bucket 如何在设置环境变量的情况下将 React 应用程序从 Github 部署到 AWS S3 存储桶 注意:我没有在 github 中推送 .env 文件 - How to deploy React app from Github to AWS S3 bucket with environment variables set Note: I didn't push .env files in github 使用 aws-sdk 通过在 s3 Bucket 上上传图像来反应原生 - react-native through upload image on s3 Bucket using aws-sdk
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM