Reputation: 1208
I'm trying to upload multiple files along with some form data using this angular package, https://github.com/danialfarid/angular-file-upload. Here's my code:
var files = ... // get the files (this is working, don't worry)
return $upload.upload({
url: '/some_resource',
type: 'POST',
headers: { 'Content-Type': 'multipart/form-data' },
data: { myObj: JSON.stringify(myObj) },
file: files
});
If there is only a single file in files
, then it uploads correctly — but if there's multiple files, then nothing is uploaded. In the docs, it says:
Upload multiple files: Only for HTML5 FormData browsers (not IE8-9) if you pass an array of files to file option it will upload all of them together in one request.
I'm not quite sure if I'm doing anything wrong or not (I'm using Chrome).
My next guess is that the issue is on the backend (I'm using Express.js). Since the request is 'multipart/form-data'
, I'm running it through multer
(https://github.com/expressjs/multer), like so:
app.post('/some_resource', multer({ dest: '../tmpUploads' }), function(req, res) {
console.log(req.files); // <- prints {} when uploading multiple files
});
Like I said, my setup works perfectly when files
only contains a single file. Any help would be greatly appreciated!
Upvotes: 2
Views: 1824
Reputation: 1208
Here's how I got this working.
var files = [...] // array of the file objects
var fileNames = [...]
// a name in [fileNames] shares the same index as the file it names in [files]
return $upload.upload({
url: '/some_resource',
type: 'POST',
headers: { 'Content-Type': 'multipart/form-data' },
data: { myObj: JSON.stringify(myObj) },
file: files,
fileFormDataName: fileNames
});
My node.js backend:
app.post('/some_resource', multer({ dest: '../tmpUploads' }), function(req, res) {
// req.files is an object, where, in terms of the frontend
// and backend variables, req.files[fileNames[i]] = files[i]
});
Upvotes: 1