【问题标题】:How to upload a file to S3 bucket with axios using React and a presigned using aws-sdk?如何使用 React 使用 axios 和使用 aws-sdk 预签名将文件上传到 S3 存储桶?
【发布时间】:2020-06-17 13:07:35
【问题描述】:

在看到这么多关于将文件上传到 S3 的帖子后,我似乎没有任何方法。我最终得到了这种方法,它似乎在几个帖子中都有效,但我真的不知道我做错了什么。

presignedUrl 我在节点服务器上使用aws-sdk 得到它,一切都很好,但是当使用以下方法上传实际文件时,它会返回协议错误;

获取文件并请求签名

let file = target.files[0];
    // Split the filename to get the name and type
    let fileParts = target.files[0].name.split('.');
    let fileName = formatFilename(fileParts[0]);
    let fileType = fileParts[1];

    const { signedRequest } = await axios.post('/upload', { fileName, fileType })

创建FormData

var bodyFormData = new FormData();
    bodyFormData.append('image', file)
    bodyFormData.append('name', fileName)

那我上传文件

const uploadImageRequest = {
        method: 'PUT',
        url: signedRequest,
        body: bodyFormData,
        headers: {
            'Content-Type': 'multipart/form-data'
        }
    }

    axios(uploadImageRequest)
        .then(result => {
            console.log("Response from s3", result)
        })
        .catch(error => {
            console.log("ERROR ", error);
        })

最后返回如下错误

ERROR  TypeError: Cannot read property 'protocol' of undefined
    at isURLSameOrigin.js:57
    at xhr.js:109
    at new Promise (<anonymous>)
    at e.exports (xhr.js:12)
    at e.exports (dispatchRequest.js:50)

【问题讨论】:

    标签: javascript reactjs amazon-s3 axios


    【解决方案1】:

    确保你在 axios 中使用的 url (signedRequest) 不是未定义的

    【讨论】:

    • 正如我所说,我有来自后端的签名网址。问题在于上传文件时
    • 这里:const { signedRequest } = await axios.post('/upload', { fileName, fileType })
    • 很可能您与 axios 一起使用的 url 是未定义的
    • 你确定 signedRequest 不是未定义的吗?
    • 你是对的。愚蠢的我。回复是data.data.signedRequest 而不是signedRequest
    猜你喜欢
    • 2021-12-18
    • 2020-03-17
    • 2019-09-27
    • 2012-05-28
    • 2017-09-24
    • 2015-08-26
    • 1970-01-01
    • 2018-01-23
    • 2021-05-05
    相关资源
    最近更新 更多