How to send selected file list when submit button

2019-08-13 03:18发布

I am using ng-file-upload to send files to server.ng-file-upload worked perfectly with upload file one by one.I am using latest chrome browser.

Sample code snippet

jsfiddle

in there files are uploaded to the server when files are selected in the file input.But what i want is that files (selected file array) should be uploaded only to the server when submit button is clicked along with other form data.

Jersey REST service

    @POST
    @Path("/manual")
    @Consumes(MediaType.MULTIPART_FORM_DATA)
    @Produces(MediaType.APPLICATION_JSON)
    public boolean insertResults(@FormDataParam("file") InputStream uploadedInputStream,@FormDataParam("file") FormDataContentDisposition fileDetail,@FormDataParam("username") String username) throws IOException {

        System.out.println(username);

        StringWriter writer = new StringWriter();
        IOUtils.copy(uploadedInputStream, writer,"UTF-8");
        String theString = writer.toString();
        System.out.println(theString);

            return Boolean.TRUE;

}

I am new to AngularJs stuff please help me to overcome this problem.

2条回答
迷人小祖宗
2楼-- · 2019-08-13 03:42

I have decided to write a descriptive answer about how to send multiples files to back end and access file details one by one.There are lack of informative answers are on the internet regarding this so this answer maybe helpful for someone.To send multiple files in AngularJs to back end you can use ng-file-upload API.You can send files when submit button click like above mentioned answer.Let assume your front end is working perfectly and can send files to server.So most of you have doubt about how to manipulate files and other details if it is a multipart form data.Here is the way how to manipulate form data.

Server end received data something like below.

Sample files data along with other form attributes

{files[0]=[org.glassfish.jersey.media.multipart.FormDataBodyPart@40ce14c9],files[1]=[org.glassfish.jersey.media.multipart.FormDataBodyPart@40ce14c9],userName=sam}

REST endpoint(using Jersey) to manupulate multipart form data

  @POST
  @Consumes(MediaType.MULTIPART_FORM_DATA)
  public void upload(FormDataMultiPart formParams){

    Map<String, List<FormDataBodyPart>> fieldsByName =   formParams.getFields();

       for (List<FormDataBodyPart> fields : fieldsByName.values()) {
            for (FormDataBodyPart field : fields){

 // Check if fields are files(If any one knows better solution to check files[] please share your answers)

                if (StringUtils.equals("files",
                  StringUtils.substringBefore(field.getName(), "["))) {

                    //To read file content
                    InputStream is = field.getEntityAs(InputStream.class);
                    String fileName = field.getName();
                    field.getMediaType();//File mimeType

                    //To get file details like size,file name,etc
                    FormDataContentDisposition f=field.getFormDataContentDisposition();
                    System.out.println(f.getFileName());

    Note: f.getType() not return the actual file type it returns mime type as   form-data to get actual mime type use FormDataBodyPart media type like above.
     }

    get other form data like user name

  else if(StringUtils.equals(field.getName(),"userName")){

          System.out.println(field.getValue());
       }
     }
   }
 }
查看更多
Lonely孤独者°
3楼-- · 2019-08-13 03:52

According to the documentation on the site and from what I'd expect - you can attach the upload function to the button and trigger it as you'd do any other function. This is an example from the GitHub documentation on ng-file-upload:

app.controller('MyCtrl', ['$scope', 'Upload', function ($scope, Upload) {
    // upload later on form submit or something similar
    $scope.submit = function() {
      if (form.file.$valid && $scope.file) {
        $scope.upload($scope.file);
      }
    };

    // upload on file select or drop
    $scope.upload = function (file) {
        Upload.upload({
            url: 'upload/url',
            data: {file: file, 'username': $scope.username}
        }).then(function (resp) {
            console.log('Success ' + resp.config.data.file.name + 'uploaded. Response: ' + resp.data);
        }, function (resp) {
            console.log('Error status: ' + resp.status);
        }, function (evt) {
            var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
            console.log('progress: ' + progressPercentage + '% ' + evt.config.data.file.name);
        });
    };
    // for multiple files:
    $scope.uploadFiles = function (files) {
      if (files && files.length) {
        for (var i = 0; i < files.length; i++) {
          Upload.upload({..., data: {file: files[i]}, ...})...;
        }
        // or send them all together for HTML5 browsers:
        Upload.upload({..., data: {file: files}, ...})...;
      }
    }
}]);

Here you can see that he's calling the $scope.upload function when the forms $scope.submit is called plus he's even checking to see if the form is valid before calling upload.

查看更多
登录 后发表回答