From 693829b95e0a1b636004053283e93fb386e4c72a Mon Sep 17 00:00:00 2001 From: Marston Ng Date: Thu, 22 Mar 2018 12:04:49 +1100 Subject: [PATCH] Exposed more request configs in UploadManager - added `reqConfigs` as a prop which accepts `accept`, `method`, `timeout` and `withCredentials` properties - added `formDataParser` as a prop which allows custom fields to be sent through in the request - referred to the suggestions in https://github.com/lionng429/react-file-uploader/pull/9/ --- src/UploadManager.js | 46 ++++++++++++++++++++++++++++++++++++++------ 1 file changed, 40 insertions(+), 6 deletions(-) diff --git a/src/UploadManager.js b/src/UploadManager.js index fffb115..f23538a 100644 --- a/src/UploadManager.js +++ b/src/UploadManager.js @@ -31,9 +31,16 @@ class UploadManager extends Component { upload(url, file) { const { + reqConfigs: { + accept = 'application/json', + method = 'post', + timeout, + withCredentials = false, + }, onUploadStart, onUploadEnd, onUploadProgress, + formDataParser, uploadErrorHandler, uploadHeader = {}, } = this.props; @@ -42,15 +49,28 @@ class UploadManager extends Component { onUploadStart(assign(file, { status: uploadStatus.UPLOADING })); } - const formData = new FormData(); - formData.append('file', file); + let formData = new FormData(); + formData = formDataParser(formData, file); + + let request = request[method.toLowerCase()](url) + .accept(accept) + .set(uploadHeader); + + if (file.type) { + request.type(file.type); + } + + if (timeout) { + request.timeout(timeout); + } + + if (withCredentials) { + request.withCredentials(); + } debug(`start uploading file#${file.id} to ${url}`, file); request - .post(url) - .accept('application/json') - .set(uploadHeader) .send(formData) .on('progress', ({ percent }) => { if (typeof onUploadProgress === 'function') { @@ -104,17 +124,31 @@ UploadManager.propTypes = { PropTypes.string, PropTypes.arrayOf(PropTypes.string), ]), + formDataParser: PropTypes.func, onUploadStart: PropTypes.func, onUploadProgress: PropTypes.func, onUploadEnd: PropTypes.func.isRequired, + reqConfigs: PropTypes.shape({ + accept: PropTypes.string, + method: PropTypes.string, + timeout: PropTypes.shape({ + response: PropTypes.number, + deadline: PropTypes.number, + }), + withCredentials: PropTypes.bool, + }), style: PropTypes.object, - uploadErrorHandler: PropTypes.func.isRequired, + uploadErrorHandler: PropTypes.func, uploadUrl: PropTypes.string.isRequired, uploadHeader: PropTypes.object, }; UploadManager.defaultProps = { component: 'ul', + formDataParser: (formData, file) => { + formData.append('file', file); + return formData; + }, uploadErrorHandler: (err, res) => { let error = null; const body = clone(res.body);