为什么我的图像无法正确上传到AWS S3?

时间:2019-06-02 04:06:59

标签: reactjs amazon-s3

我正在尝试将图像上传到AWS S3,但无法正常工作。 出现了一个文件,但文件太小而无法显示图像,因此无法在S3中正确打开。

我不确定我的哪些参数错误。 我要上传的文件称为picture.jpg。

这是我当前的代码:

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;

谢谢。

1 个答案:

答案 0 :(得分:0)

e.target是对输入的React引用。该值存储在当前属性中。在您的参数中尝试以下操作:Body: e.target.current.files[0],

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

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