Skip to content

Instantly share code, notes, and snippets.

@mgvez
Created February 16, 2016 15:26
Show Gist options
  • Save mgvez/8d3aee538e1102243ab7 to your computer and use it in GitHub Desktop.
Save mgvez/8d3aee538e1102243ab7 to your computer and use it in GitHub Desktop.
Trying to figure out the best way to send a file in chunks using Redux
//save-file action
import { CALL_API } from '../middleware/api'
const CHUNK_SIZE = 100 * 1024;
function sendChunk(dispatch, file, rangeStart = 0) {
let rangeEnd = rangeStart + CHUNK_SIZE;
if (rangeEnd > file.size) {
rangeEnd = file.size;
}
const chunk = file.slice(rangeStart, rangeEnd);
const data = new FormData();
data.append('chunk', chunk);
data.append('name', file.name);
data.append('totalSize', file.size);
data.append('currentSize', rangeEnd);
const chunkRequestAction = dispatch({
[CALL_API]: {
types: ['SEND_FILE_REQUEST', 'SEND_FILE_SUCCESS', 'SEND_FILE_FAILURE'],
route: `file`,
data,
},
});
if (rangeEnd === file.size) {
return chunkRequestAction;
}
return chunkRequestAction.then(() => sendChunk(dispatch, file, rangeEnd));
}
export function sendFile(fileInput) {
return (dispatch) => {
return sendChunk(dispatch, fileInput.files[0]);
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment