当前位置: 动力学知识库 > 问答 > 编程问答 >

AngularJs: upload mutiple files from different sources

问题描述:

I am trying to upload two different files, an image and a pdf file, each from a different input as follows:

<div class="form-group" ng-class="libraries.error.img[0] ? 'has-error' : ''">

<label for="img">Image</label>

<input type="file" accept="image/*" ngf-select="" ngf-multiple="true" class="form-control" id="img" name="img" placeholder="Image" ng-model="libraries.library.img">

<p ng-if="libraries.error.img[0]" style="color: red">{{libraries.error.img[0]}}</p>

</div>

<div class="form-group" ng-class="libraries.error.document[0] ? 'has-error' : ''">

<label for="document">Document</label>

<input type="file" accept="application/pdf" ngf-select="" class="form-control" id="document" name="document" placeholder="Document" ng-model="libraries.library.document">

<p ng-if="libraries.error.document[0]" style="color: red">{{libraries.error.document[0]}}</p>

</div>

In the services file, I am sending it using the following:

store: function (library) {

console.log(library);

return Upload.upload({

url: 'api/libraries',

method: 'POST',

fields: {name: library.name, location: library.location},

file: [library.img, library.document]

});

},

But when I try to fetch the files at the server side as follows:

return $_FILES;

I keep getting:

[] No Properties

However when I change file to

file: library.img

meaning, I pass only one file, it works.

I am using ng-file-upload with AngularJS and the server side is Laravel

Any idea to solve this issue allowing both files to be sent to the server?!

网友答案:

I've had the same issue, and I was able to fix it by giving the JSON object for each file a different name (drawing inspiration from here). If I did not rename the objects, the server would receive the correct number of files but all of them would be identical. So if you were to apply this, your code would be:

store: function (library) {
   console.log(library);
   return  Upload.upload({
   url: 'api/libraries',
   method: 'POST',
   fields: {name: library.name, location: library.location},
   file: [library.img, library.document]
   fileFormDataName: [name1, name2]
     });
   },

I believe the names can be anything as long as they are unique. However, you now have to process the objects separately on your server side. I am not familiar with how you might do that in PHP, but on my Rails back-end, I can collect all of the files by their class:

files = params.values.find_all { |value| value.class == ActionDispatch::Http::UploadedFile }

Then I simply assign each file to the appropriate attribute of my model.

分享给朋友:
您可能感兴趣的文章:
随机阅读: