How to upload a file to S3 bucket with axios using React and a presigned using aws-sdk?

Viewed 3239

After seeing so many posts in regards with uploading files to S3 for me seem to not working any method. I've ended up with this method which seem to work in couple of posts and I don't really know what I am doing wrong.

The presignedUrl I get it using the aws-sdk on node server and everything is fine with that but when it comes to upload the actual file using the following method it return a protocol error;

Get the file and make a request to sign it

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 })

Create a FormData

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

Then I will upload the file

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);
        })

Finally it returns the following 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)
1 Answers

Make sure the url (signedRequest) you are using in axios is not undefined

Related