S3使用秘钥上载(react-dropzone-uploader)

时间:2019-07-19 20:51:20

标签: reactjs amazon-s3

(更新:请参见下文)我正在将react-dropzone-uploader实现到我的React项目中,到目前为止,使用和自定义它都很棒。我希望这些上传到POST到我的S3存储桶中。

文档HERE为我提供了一个如何使用presigned upload url进行操作的示例。我可以使用AWS_ACCESS_KEY_IDAWS_SECRET_ACCESS_KEY(下面的最后一个代码段)进行身份验证,但是我不确定如何使 dropzone 逻辑正确上传。


以下是软件包的默认功能之一:

const Standard = () => {
  const getUploadParams = () => {
    return { url: 'https://httpbin.org/post' }
  }

  const handleChangeStatus = ({ meta }, status) => {
    console.log(status, meta)
  }

  const handleSubmit = (files, allFiles) => {
    console.log(files.map(f => f.meta))
    allFiles.forEach(f => f.remove())
  }

  return (
    <Dropzone
      getUploadParams={getUploadParams}
      onChangeStatus={handleChangeStatus}
      onSubmit={handleSubmit}
      styles={{ dropzone: { minHeight: 200, maxHeight: 250 } }}
    />
  )
}

<Standard />

...这是调用API的文档建议的实现,该API返回预签名的AWS S3 url(验证凭证):

const getUploadParams = async ({ meta: { name } }) => {
  const { fields, uploadUrl, fileUrl } = await myApiService.getPresignedUploadParams(name)
  return { fields, meta: { fileUrl }, url: uploadUrl }
}

(更新:)
好的,我可以使用authAWS.js文件中的以下代码来连接到S3:

var AWS = require('aws-sdk');

AWS.config.update({
  region: 'us-east-2',
  accessKeyId: '<access_key>',
  secretAccessKey: '<secret_key>'
})

export const s3 = new AWS.S3({
  params: {
    Bucket: 'BUCKETNAME'
  },
  apiVersion: '2006-03-01',
});

export const list_ = s3.listObjects({Delimiter: '/invoice/'}, function(err, data) {
  if (err) {
    return alert('There was an error listing your objects: ' + err.message);
  } else {
    console.log(data)
  }
});

1 个答案:

答案 0 :(得分:1)

getUploadParams = async ({ meta }) => {
    try {
        console.log(meta);
        const { name, type } = meta;
        const res = await axios.get('/s3/sign', {
            params: {
                fileName: name,
                contentType: type
            },
            headers: {
                "Access-Control-Allow-Origin": "https://localhost:3000",
                "Access-Control-Allow-Credentials": "true",
                "content-type": type
            }
        }
        );
        console.log(res)
        return res.data.signedUrl;
    } catch (error) {
        console.log(error);
    }
}

我具有从S3存储桶获取URL的功能,但它们引发了CORS问题错误。

我希望它能对您有所帮助。