I'm trying to upload an image to AWS S3 but it's not working. A file appears but it is too small to be the image and does not open properly in S3.

I'm not sure which of my parameters are wrong. The file I'm trying to upload is called picture.jpg.

Here's my current code:

import React , {Component} from 'react';
import logo from './logo.svg';
import './App.css';
import AWS from 'aws-sdk';

AWS.config.update({
    accessKeyId: "xxxxxx",
    secretAccessKey: "xxxxxx",
});

const s3 = new AWS.S3();


const u = ''
const config = {
    bucketName: 'mybucket', // name of the bucket
    region: 'us-east-1',
    accessKeyId: 'xxxxxx',
    secretAccessKey: 'xxxxxxx',
}

class App extends Component {
  constructor() {
    super();
    this.state ={
      url: u,
    }
    this.upload = this.upload.bind(this);
  }

  upload(e) {
    var params = { 
      Body: e.target.files[0],
      Bucket: "mybucket", 
      Key: "picture.jpg", // call the new image Thisnewpic.jpg
    };
    s3.putObject(params, function(err, data) {
     if (err) console.log(err, err.stack); // an error occurred
     else     console.log(data);           // successful response
      });

  }

  render() {
    return ( <div>
      Upload AWS S3
      <input 
        type="file"
        onChange={this.upload}
      />
      <button onClick={this.delete}>Delete</button>
      <img src={this.state.url} />
    </div>);
  }
}

export default App;

Thanks.

1 Answers

0
Raymond Mutyaba On

e.target is a React reference to the input. The value is stored in the current property. Try this in your params: Body: e.target.current.files[0],

Refs: https://reactjs.org/docs/refs-and-the-dom.html#accessing-refs

Inputs: https://reactjs.org/docs/uncontrolled-components.html#the-file-input-tag