Skip to content

Instantly share code, notes, and snippets.

@jens1101
Last active May 22, 2018 09:04
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jens1101/fb1ea139e0eff2dc3baea639c8b52a95 to your computer and use it in GitHub Desktop.
Save jens1101/fb1ea139e0eff2dc3baea639c8b52a95 to your computer and use it in GitHub Desktop.
Upload files via AJAX
angular.module('uploadFile', []).service('uploadService', ['$http', function ($http) {
this.uploadFile = function () {
var field = document.createElement('input')
field.setAttribute('type', 'file')
field.setAttribute('accept', '.json, application/json')
field.onchange = function () {
var data = new FormData()
data.append('connectionId', 'banana')
data.append('fileToImport', field.files[0])
$http.post('http://www.example.com/form-submit', data, {
transformRequest: angular.identity,
headers: {
'Content-Type': undefined
}
}).then(function (response) {
alert('Submit successful! Server says: ' + response.data)
})
}
field.click()
}
}])
function uploadFile () {
var field = document.createElement('input')
field.setAttribute('type', 'file')
field.setAttribute('accept', '.json, application/json')
field.onchange = function () {
var data = new FormData()
data.append('connectionId', 'banana')
data.append('fileToImport', field.files[0])
$.ajax({
url: 'http://www.example.com/form-submit',
type: 'POST',
processData: false, // important
contentType: false, // important
data: data,
success: function (response) {
alert('Submit successful! Server says: ' + response.data)
}
})
}
field.click()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment