How to upload files to AWS S3 bucket from the react frontend

Viewed 13450

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.

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. 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>
2 Answers
Related