uppy
Version:
Almost as cute as a Puppy :dog:
246 lines (195 loc) • 8.11 kB
JavaScript
;
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _Promise = typeof Promise === 'undefined' ? require('es6-promise').Promise : Promise;
var Plugin = require('./Plugin');
var settle = require('promise-settle');
var UppySocket = require('../core/UppySocket');
var Utils = require('../core/Utils');
module.exports = function (_Plugin) {
_inherits(XHRUpload, _Plugin);
function XHRUpload(core, opts) {
_classCallCheck(this, XHRUpload);
var _this = _possibleConstructorReturn(this, _Plugin.call(this, core, opts));
_this.type = 'uploader';
_this.id = 'XHRUpload';
_this.title = 'XHRUpload';
// Default options
var defaultOptions = {
formData: true,
fieldName: 'files[]',
method: 'post',
metaFields: null,
responseUrlFieldName: 'url',
bundle: true,
headers: {},
getResponseData: function getResponseData(xhr) {
return JSON.parse(xhr.response);
},
getResponseError: function getResponseError(xhr) {
return new Error('Upload error');
}
};
// Merge default options with the ones set by user
_this.opts = _extends({}, defaultOptions, opts);
_this.handleUpload = _this.handleUpload.bind(_this);
return _this;
}
XHRUpload.prototype.createFormDataUpload = function createFormDataUpload(file, opts) {
var formPost = new FormData();
var metaFields = Array.isArray(opts.metaFields) ? opts.metaFields
// Send along all fields by default.
: Object.keys(file.meta);
metaFields.forEach(function (item) {
formPost.append(item, file.meta[item]);
});
formPost.append(opts.fieldName, file.data);
return formPost;
};
XHRUpload.prototype.createBareUpload = function createBareUpload(file, opts) {
return file.data;
};
XHRUpload.prototype.upload = function upload(file, current, total) {
var _this2 = this;
var opts = _extends({}, this.opts, this.core.state.xhrUpload || {}, file.xhrUpload || {});
this.core.log('uploading ' + current + ' of ' + total);
return new _Promise(function (resolve, reject) {
var data = opts.formData ? _this2.createFormDataUpload(file, opts) : _this2.createBareUpload(file, opts);
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener('progress', function (ev) {
if (ev.lengthComputable) {
_this2.core.emit('core:upload-progress', {
uploader: _this2,
id: file.id,
bytesUploaded: ev.loaded,
bytesTotal: ev.total
});
}
});
xhr.addEventListener('load', function (ev) {
if (ev.target.status >= 200 && ev.target.status < 300) {
var resp = opts.getResponseData(xhr);
var uploadURL = resp[opts.responseUrlFieldName];
_this2.core.emit('core:upload-success', file.id, resp, uploadURL);
if (uploadURL) {
_this2.core.log('Download ' + file.name + ' from ' + file.uploadURL);
}
return resolve(file);
} else {
var error = opts.getResponseError(xhr) || new Error('Upload error');
error.request = xhr;
_this2.core.emit('core:upload-error', file.id, error);
return reject(error);
}
// var upload = {}
//
// if (opts.bundle) {
// upload = {files: files}
// } else {
// upload = {file: files[current]}
// }
});
xhr.addEventListener('error', function (ev) {
_this2.core.emit('core:upload-error', file.id);
return reject(new Error('Upload error'));
});
xhr.open(opts.method.toUpperCase(), opts.endpoint, true);
Object.keys(opts.headers).forEach(function (header) {
xhr.setRequestHeader(header, opts.headers[header]);
});
xhr.send(data);
_this2.core.on('core:upload-cancel', function (fileID) {
if (fileID === file.id) {
xhr.abort();
}
});
_this2.core.on('core:cancel-all', function () {
// const files = this.core.getState().files
// if (!files[file.id]) return
xhr.abort();
});
_this2.core.emit('core:upload-started', file.id);
});
};
XHRUpload.prototype.uploadRemote = function uploadRemote(file, current, total) {
var _this3 = this;
var opts = _extends({}, this.opts, file.xhrUpload || {});
return new _Promise(function (resolve, reject) {
_this3.core.emit('core:upload-started', file.id);
fetch(file.remote.url, {
method: 'post',
credentials: 'include',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(_extends({}, file.remote.body, {
endpoint: opts.endpoint,
size: file.data.size,
fieldname: opts.fieldName
}))
}).then(function (res) {
if (res.status < 200 && res.status > 300) {
return reject(res.statusText);
}
res.json().then(function (data) {
var token = data.token;
var host = Utils.getSocketHost(file.remote.host);
var socket = new UppySocket({ target: host + '/api/' + token });
socket.on('progress', function (progressData) {
return Utils.emitSocketProgress(_this3, progressData, file);
});
socket.on('success', function (data) {
_this3.core.emit('core:upload-success', file.id, data, data.url);
socket.close();
return resolve();
});
});
});
});
};
XHRUpload.prototype.selectForUpload = function selectForUpload(files) {
var _this4 = this;
return settle(files.map(function (file, i) {
var current = parseInt(i, 10) + 1;
var total = files.length;
if (file.isRemote) {
return _this4.uploadRemote(file, current, total);
} else {
return _this4.upload(file, current, total);
}
})
// if (this.opts.bundle) {
// uploaders.push(this.upload(files, 0, files.length))
// } else {
// for (let i in files) {
// uploaders.push(this.upload(files, i, files.length))
// }
// }
);
};
XHRUpload.prototype.handleUpload = function handleUpload(fileIDs) {
if (fileIDs.length === 0) {
this.core.log('XHRUpload: no files to upload!');
return Promise.resolve();
}
this.core.log('XHRUpload is uploading...');
var files = fileIDs.map(getFile, this);
function getFile(fileID) {
return this.core.state.files[fileID];
}
return this.selectForUpload(files).then(function () {
return null;
});
};
XHRUpload.prototype.install = function install() {
this.core.addUploader(this.handleUpload);
};
XHRUpload.prototype.uninstall = function uninstall() {
this.core.removeUploader(this.handleUpload);
};
return XHRUpload;
}(Plugin);
//# sourceMappingURL=XHRUpload.js.map