【问题标题】:S3 creating empty files when uploading a file from React contact form using AxiosS3在使用Axios从React联系表单上传文件时创建空文件
【发布时间】:2021-03-28 20:45:15
【问题描述】:

我创建了一个测试联系表单,用户可以在其中上传图片附件。

  • presignedURL AWS Lambda 函数工作正常
  • 图像文件 (blob) 在 html 中显示为图像,因此添加正确
  • 发布图片后,我收到成功的 200 响应,并且文件出现在 S3 中

但是,在 S3 中所有文件都显示为空。大小似乎会根据链接大小的长度而变化(例如,blob 是 63B,硬编码链接的大小会有所不同),因此它似乎只是将链接作为数据,而不是实际图像。我检查了很多次我的 axios 语法是否正确,并在 SO 中经历了许多线程,但无法弄清楚我做错了什么。

AWS Lambda 生成预签名 URL:

const AWS = require('aws-sdk')
AWS.config.update({ region: 'eu-west-2' })
const s3 = new AWS.S3();

const uploadBucket = 'xxx-bucket'

exports.handler = async (event) => {
  const result = await getUploadURL()
  console.log('Result: ', result)
  return result
};

const getUploadURL = async function() {
  console.log('getUploadURL started')
  let actionId = Date.now()

  var s3Params = {
    Bucket: uploadBucket,
    Key:  `${actionId}.jpg`,
    ContentType: 'image/jpeg',
    CacheControl: 'max-age=31104000',
    ACL: 'public-read'
  };

  return new Promise((resolve, reject) => {
    // Get signed URL
    let uploadURL = s3.getSignedUrl('putObject', s3Params)
    resolve({
      "statusCode": 200,
      "isBase64Encoded": false,
      "headers": {
        "Access-Control-Allow-Origin": "*"
      },
      "body": JSON.stringify({
          "uploadURL": uploadURL,
          "photoFilename": `${actionId}.jpg`
      })
    })
  })
}

反应前端:

class QuoteForm extends Component {

  constructor(props) {
    super(props);
    this.state = {
      file:null,
    };
  };

  onContactNameChange(e){
    this.setState({ContactName:e.target.value});
  };

  onFileChange(e){
    let [file] = e.target.files;
    if (file) {
      this.setState({
        file: URL.createObjectURL(e.target.files[0]),
      });
      console.log(file);
    }
  };

  async handleSubmit(e){
    e.preventDefault();
  
      axios.post(`https://xxxx/`)
      .then(res => {
            console.log(res)
            const url = res.data.uploadURL;

            const axiosConfig = {
                headers: { 
                    "Content-Type": "image/jpeg",
                    "Cache-Control": 'max-age=31104000' 
                }
            }

            axios.put(url, this.state.file, axiosConfig)
                .then(response => {console.log(response)}).catch(err => {console.log(err.response)
            });
        });

    }
  
  render() {
    return (
      <form onSubmit={this.handleSubmit.bind(this)}>
            <input 
                type="file"
                name="file"
                id="fileUpload" 
                onChange={this.onFileChange.bind(this)}
            />

            <img src={this.state.file} alt="img" />

            <button 
                className="large"
                style={{marginTop:"1.25rem"}} >
                Submit
            </button>
      </form>
    );
  }
}

S3 存储桶文件:

我只是不明白为什么 S3 存储桶中的文件是空的。

【问题讨论】:

    标签: javascript node.js reactjs amazon-s3 axios


    【解决方案1】:

    好的,我知道我的问题是什么。 createObjectURL 在我的前端 React 代码中显然不能用于将文件上传到服务器,因为它实际上并不包含文件,而只包含 URL。我将整个onFileChange(e) 函数缩短为下面的函数,S3 开始接收实际文件。

      onFileChange(e){
            const [selectedFile] = e.target.files;
        if (selectedFile) {
                this.setState({file:selectedFile})
            }
      };
    

    【讨论】:

      猜你喜欢
      • 2015-03-09
      • 1970-01-01
      • 2020-02-11
      • 2013-01-11
      • 1970-01-01
      • 2021-12-09
      • 2021-04-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多