Skip to content

Instantly share code, notes, and snippets.

@Ifmr24
Created August 25, 2019 18:13
Show Gist options
  • Save Ifmr24/1135dd74f9043313f85ae939d53ff175 to your computer and use it in GitHub Desktop.
Save Ifmr24/1135dd74f9043313f85ae939d53ff175 to your computer and use it in GitHub Desktop.
S3 Upload Redux Actions
import axios from 'axios';
import shortid from 'shortid';
export const STARTING_UPLOAD = 'STARTING_UPLOAD';
export const SUCCESS_UPLOAD = 'SUCCESS_UPLOAD';
export const ERROR_UPLOAD = 'ERROR_UPLOAD';
export const startingUpload = () => {
return {
type: STARTING_UPLOAD
};
};
export const successUpload = (payload) => {
return {
type: SUCCESS_UPLOAD,
payload: payload
};
};
export const errorUpload = (payload) => {
return {
type: ERROR_UPLOAD,
payload: payload
};
};
export const uploadFileThunk = (ref, folder) => {
return async (dispatch, getState) => {
let file = ref.current.files[0];
let fileParts = file.name.split('.');
let fileName = shortid.generate() + "_" + fileParts[0];
let fileType = fileParts[1];
dispatch(startingUpload());
await axios.post("http://localhost:5000/api/uploadavatar", {
fileName,
fileType,
folder
}).then(async res => {
let data = res.data.data.returnData;
let signedRequest = data.signedRequest
let url = data.url;
let options = {
headers: {
'Content-Type': fileType
}
};
await axios.put(signedRequest, file, options)
.then(res => {
dispatch(successUpload(url));
}).catch(err => {
dispatch(errorUpload(err))
})
}).catch(err => {
dispatch(errorUpload(err))
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment