2
votes

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!

1
Firstly I would try to use i.e. Fiddler to check whether the problem is on the client or on the server. Secondly, try to add names for the files: fileName or fileFormDataName properties. I was trying out this module, but since I couldn't drop support for IE8/9, now I'm using this jQuery plugin and it works great.Kamil R
Adding the fileFormDataName property totally worked! Thanks!Cody
@Cody, any chance you'd show us how you got it working ? I'm facing the same issue and tried playing a bit with fileFormDataName, but not very efficiently so far... any help you could provide would be greatly appreciated :)Pierre-Adrien
@PA.Buisson just posted my solution as an answer!Cody

1 Answers

1
votes

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]
});