Skip to content

Instantly share code, notes, and snippets.

@Dewep
Created January 10, 2017 14:30
Show Gist options
  • Save Dewep/a7264f1c8e3e0976f60ae96a43b19617 to your computer and use it in GitHub Desktop.
Save Dewep/a7264f1c8e3e0976f60ae96a43b19617 to your computer and use it in GitHub Desktop.
MultiPart Uploader
function onChange(event) {
if (this.fileUploading) {
this.appEventsService.emit("error", "A file is already uploading.")
} else if (!event || !event.target || !event.target.files[0]) {
this.appEventsService.emit("error", "Input file error.")
} else if (!this.user || !this.user._id) {
this.appEventsService.emit("error", "User not found.")
} else {
var multiPartUploader = new MultiPartUploader({
url: this.apiService.baseApiPath + '/message/user/' + this.user._id + '/attachment',
authorization: this.apiService.getApiKey(),
asJSON: true
})
this.fileUploading = {
name: event.target.files[0].name,
size: event.target.files[0].size,
percent: 0,
multiPartUploader: multiPartUploader
}
multiPartUploader.addFormData("attachment", event.target.files[0])
multiPartUploader.onProgress(function (progressEvent) {
this.fileUploading.percent = Math.round(progressEvent.loaded * 100 / progressEvent.total)
}.bind(this))
multiPartUploader.upload().then(function (res) {
this.fileUploading = null
}.bind(this)).catch(function (err) {
this.fileUploading = null
this.appEventsService.emit("error", err.response || err)
}.bind(this))
if (this.messagesList) {
setTimeout(function () {
this.messagesList.nativeElement.scrollTop = this.messagesList.nativeElement.scrollHeight
}.bind(this), 0)
}
}
}
(function(exports) {
var MultiPartUploader = function (options) {
this._url = options.url
this._method = options.method || "POST"
this._headers = options.headers || {}
this._timeout = options.timeout || 10000
this._asJSON = options.asJSON === true
this._withCredentials = options.withCredentials !== false
if (options.authorization) {
this._headers['Authorization'] = options.authorization
}
this._xhr = null
this._formData = new FormData()
this._onProgress = function () {}
}
MultiPartUploader.prototype.addFormData = function (field, data) {
this._formData.append(field, data)
return this
}
MultiPartUploader.prototype.onProgress = function (handler) {
this._onProgress = handler
return this
}
MultiPartUploader.prototype.abort = function () {
if (this._xhr && this._xhr.readyState != 4) {
this._xhr.abort()
return true
}
return false
}
MultiPartUploader.prototype.upload = function () {
var parseHeaders = function (headers) {
var parsed = {}
if (!headers) {
return parsed
}
headers.split('\n').map(function (line) {
var i = line.indexOf(':')
var key = line.slice(0, i).trim().toLowerCase()
var val = line.slice(i + 1).trim()
if (key) {
parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val
}
})
return parsed
}
var isSuccessCode = function (status) {
return (status >= 200 && status < 300) || status === 304
}
return new Promise(function (resolve, reject) {
this._xhr = new XMLHttpRequest()
var complete = function (type) {
if (type === undefined) {
type = isSuccessCode(this._xhr.status) ? 'success' : 'error'
}
var response = this._xhr.response
if (this._asJSON) {
try {
response = JSON.parse(response)
} catch (e) {}
}
var data = {
type: type,
responseText: this._xhr.response,
response: response,
status: this._xhr.status,
headers: parseHeaders(this._xhr.getAllResponseHeaders())
}
if (type === 'success') {
resolve(data)
} else {
reject(data)
}
}.bind(this)
this._xhr.timeout = this._timeout
this._xhr.upload.onprogress = this._onProgress
this._xhr.onload = function () {
complete()
}
this._xhr.onerror = function () {
complete('error')
}
this._xhr.ontimeout = function () {
complete('timeout')
}
this._xhr.onabort = function () {
complete('abort')
}
this._xhr.open(this._method, this._url, true)
this._xhr.withCredentials = this._withCredentials
Object.keys(this._headers).forEach(function (key) {
this._xhr.setRequestHeader(key, this._headers[key])
}.bind(this))
this._xhr.send(this._formData)
}.bind(this))
}
exports.MultiPartUploader = MultiPartUploader
})(window)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment