首页 > 解决方案 > Material ui dropzone S3 上传器

问题描述

如果以前有人问过这个问题,请原谅我。我是新手,我正在开发一项使用https://yuvaleros.github.io/material-ui-dropzone/将文件上传到 S3 存储桶的功能。有人可以帮我解决这个问题。我正在使用库提供的 onDrop 方法调用我的 getPresignedUrl 方法,但我无法弄清楚如何将实际文件上传到 S3?

export default function UploadFiles(props) {
  const { formData, handleChange } = props;
  const classes = useStyles();
  
  const uploadFiles = (fileName) => {

    api.uploadFiles(fileName).then((res) => {
      const { statusCode } = res.data;
      if (statusCode === 200) {
        //do something
        // setSnackbar({
        //   ...snackbar,
        //   ...{
        //     show: true,
        //     message: `Success`,
        //     type: "success",
        //   },
        // });

      } else {
        console.log("this errored out");
        //do something
      }
    });

  }
  return (
    <React.Fragment>
      
     <div className={classes.dropzonePreviewHeader}>
     <DropzoneArea
      showPreviews={true}
      showPreviewsInDropzone={false}
      useChipsForPreview
      previewGridProps={{container: { spacing: 1, direction: 'row' }}}
      previewChipProps={{classes: { root: classes.previewChip } }}
      previewText="Selected files"
      onDrop={e => {
        e.forEach(item => uploadFiles(item.name));
      }}
  /></div>
    </React.Fragment>
  );
}

标签: amazon-s3file-uploadmaterial-uidropzonereact-dropzone

解决方案


有一个现有的图书馆可以做到这一点:这里

阅读我的示例代码:

import S3 from 'aws-s3';

const config = {
    bucketName: 'myBucket',
    dirName: 'photos', /* optional */
    region: 'eu-west-1',
    accessKeyId: 'ANEIFNENI4324N2NIEXAMPLE',
    secretAccessKey: 'cms21uMxçduyUxYjeg20+DEkgDxe6veFosBT7eUgEXAMPLE',
    s3Url: 'https://my-s3-url.com/', /* optional */
}

const S3Client = new S3(config);
/*  Notice that if you don't provide a dirName, the file will be automatically uploaded to the root of your bucket */

/* This is optional */
const newFileName = 'my-awesome-file';

S3Client
    .uploadFile(file, newFileName)
    .then(data => console.log(data))
    .catch(err => console.error(err))

  /**
   * {
   *   Response: {
   *     bucket: "your-bucket-name",
   *     key: "photos/image.jpg",
   *     location: "https://your-bucket.s3.amazonaws.com/photos/image.jpg"
   *   }
   * }
   */
});

推荐阅读