0

I am able to upload single image with form data. But now i want to upload multiple images with form data.I have referred many answers but still in server code am getting null for files.

In Angular controller, form data appends list of files,But which is empty in Spring controller. Please help,

Entity

@Id
@Column(name="productId")
private Integer productId;

@Column(name="itemName", unique = true)
private String itemName;
     
@Column(name="twoDByteArray",columnDefinition="mediumblob")
private byte[][] twoDByteArray=new byte[10][];

Controller.java

@RequestMapping(value = "/addProduct", consumes = { "multipart/form-data" }, method = RequestMethod.POST)
@ResponseBody
public Product addProduct(@RequestPart("files") MultipartFile[] files, @RequestPart("product") Product product,HttpSession session, HttpServletRequest request, HttpServletResponse response)
        throws IOException, SerialException, SQLException {

    if(file!=null){
        byte[][] data1 = new byte[10][];  
        byte[] contents = file.getBytes();
        data1[0] = contents;
        product.setTwoDByteArray(data1);
    }
    return product;
}

Controller.js

scope.addProduct = function (product,files) {
    alert(product);
    alert(files);
        scope.files = files;
        if (files && files.length) {
            Upload.upload({
                url: '/Admin_Test/addProduct',
                /*fields: {'username': 'Roja'}, // additional data to send
                files: files*/
                data: {
                    files: files,'product':product
                }
            }).then(function (response) {
                timeout(function () {
                    scope.result = response.data;
                });
            }, function (response) {
                if (response.status > 0) {
                    scope.errorMsg = response.status + ': ' + response.data;
                }
            }, function (evt) {
                scope.progress = 
                    Math.min(100, parseInt(100.0 * evt.loaded / evt.total));
            });
        }
    };

Html

<input type="file" ngf-select ng-model="$files" multiple 
 name="file" accept="image/*" ngf-max-size="2MB" required /> 
        <!--  <div class="col-sm-4 form-group ">
            <input type="file" name="file" id="file" multiple="true" >
        </div> -->
                        
<input type="submit" name="Submit" class="btn btn-primary"
value="Submit" ng-click="addProduct(product,$files)" />
                        

edit

After using ng-upload, i can see image details in console,but which are not present in file.

DEBUG CommonsMultipartResolver:287 - Found multipart file [files[0]] of size 3384 bytes with original filename [hh1.png], stored in memory

DEBUG CommonsMultipartResolver:287 - Found multipart file [files[1]] of size 8591 bytes with original filename [hh.png], stored in memory

Thank you.

Community
  • 1
  • 1
Hema
  • 988
  • 1
  • 16
  • 38
  • http://jsfiddle.net/p7uuy2as/ try this code using ng-file-upload library – zabusa Dec 19 '17 at 06:19
  • check the https://github.com/danialfarid/ng-file-upload you will find it in here – zabusa Dec 19 '17 at 06:29
  • @zabusa with ng-upload also same issue in server side – Hema Dec 19 '17 at 07:55
  • multiple files in one request is not good. You can't handle errors e.g. what do you do, if 1 file is not able to be uploaded? cancel whole request? some files were already uploaded, rollback? Just do 1 request per file and you are safe. – Develobba Dec 20 '17 at 06:36
  • 1
    @CodeNashor But my requirement is to upload multiple images,lets say with form data of 3 fields, need to submit those images also. And entire object to be saved.Any help..? – Hema Dec 20 '17 at 06:40
  • You still can upload the files one by one without users knowledge. Its much more safer, ng-upload has problems with multiple files and crossbrowser especially IE 10+ does some weird things in some situations. – Develobba Dec 20 '17 at 06:43
  • @CodeNashor So u mean to say on each selection of image.But how to handle java side.?I want to save in single object itself,at one time to database.. – Hema Dec 20 '17 at 06:51
  • @CodeNashor can you give me a over view of it. So tht i will try to implement it – Hema Dec 20 '17 at 06:52
  • Create Database object on the first request and store it in database, all other requests will just update the database entry. The problem here: the following requests have to know, that they just update a existing database entry, not creating a new one. Hope you have something like 'id: 1, files: files', then you send the request like 'id 1: file: file1' next request 'id: 1, file: file2'. In Java you create the object on first request, and update it on the following requests with the same id. – Develobba Dec 20 '17 at 06:53
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/161580/discussion-between-hema-and-codenashor). – Hema Dec 20 '17 at 06:56
  • https://stackoverflow.com/a/46708678/7256477 try this – Raju Dec 27 '17 at 13:42
  • @Raju I need to submit along with form data in same request – Hema Dec 28 '17 at 06:37
  • use FormData you can add files and data in single Object thats code is also availabel in above example ($scope.submitdata function) – Raju Dec 28 '17 at 07:29

2 Answers2

2

try this
frontend

function uploadFiles(files){
        return Upload.upload({
            url : "your_url",
            method : "POST",
            headers: {
                "Content-Type": undefined
            },
            file: files,
            arrayKey: ''
        });
}

backend

@RequestMapping(value = {"/uploadFiles"}, method = RequestMethod.POST)
public ResponseEntity<?> uploadFiles(@RequestParam("file") List<MultipartFile> file){...}
lefas
  • 32
  • 1
  • 5
0

Try below code.

Angular Controller

Upload.upload({
   url: '/Admin_Test/addProduct',
   files: files,
   data: product
})

Spring Controller

@RequestMapping(value = "/addProduct", method = RequestMethod.POST)
@ResponseBody
public Product addProduct(@RequestPart("files") MultipartFile[] files, Product product,HttpSession session, HttpServletRequest request, HttpServletResponse response)
        throws IOException, SerialException, SQLException {
    if(files!=null){
        System.out.println("In multiple img..."+files +"..."+product);
        System.out.println(product +""+ files);//null null
    }
}
hrdkisback
  • 898
  • 8
  • 19
  • Thank you for ur response.. `org.springframework.web.multipart.support.MissingServletRequestPartException: Required request part 'product' is not present` am getting bad request error – Hema Dec 28 '17 at 06:12
  • What you got in `alert(product);`? And Can you post your POJO `Product` class ? – hrdkisback Dec 28 '17 at 07:22
  • In alert i am getting product object with proper values. I have added POJO in my question – Hema Dec 28 '17 at 07:29
  • Make sure angular's `product` object and your Java POJO `Product` class have same attributes so spring will Jackson Mapper automatically map your object's attribute. – hrdkisback Dec 28 '17 at 07:32
  • I am getting this issue only for multiple files upload, for single file upload product will reach to server side controller – Hema Dec 28 '17 at 07:35
  • Have you added `` in `application context` refer this link https://stackoverflow.com/questions/32990908/geting-http-status-400-required-multipartfile-parameter-file-is-not-present – hrdkisback Dec 28 '17 at 07:37
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/162076/discussion-between-hrdkisback-and-hema). – hrdkisback Dec 28 '17 at 07:37
  • @Hema, Try to `@RequestMapping(value = "/addProduct", method = RequestMethod.POST, headers = ("content-type=multipart/*"))` add `headers`. – hrdkisback Dec 29 '17 at 19:56