0

I wish to send my localhost (in spring boot server) a selected image from the user using AngularJS and add data object in BD using JAX-RS.

-Code HTML:

<form role="form" enctype="multipart/form-data" name="myForm" ng-submit="uploadfile()">
<label class="control-label">Image:</label> 
<input type="file" class="form-control " file-model="Image" > 
<input type="text" class="form-control " ng-model="name" > 
 <input type="text" class="form-control " ng-model="lastname" > 
<button type="submit"> save</button>
</form>

--code AngularJS;

var app = angular.module('Mainapp', ['ngRoute','file-model','ui.bootstrap']);
app.directive('fileModel', ['$parse', function ($parse) {
    return {
       restrict: 'A',
       link: function(scope, element, attrs) {
          var model = $parse(attrs.fileModel);
          var modelSetter = model.assign;

          element.bind('change', function(){
             scope.$apply(function(){
                modelSetter(scope, element[0].files[0]);
             });
          });
       }
    };
 }]);

app.service('fileUpload', ['$http', function ($http) {
    this.uploadFileToUrl = function(file, uploadUrl){
        var fd = new FormData();
        //fd.append('file', file);
       angular.forEach(file, function(file) {
            fd.append('file', file);
        });

        $http.post(uploadUrl, fd, {
            transformRequest: angular.identity,
            headers: {'Content-Type': undefined}
        }).then(function(response) {
            console.log("done post "+response);
    }).catch(function(e) {
        console.log('failed to post: ', e);
        throw e;
    })

    }
}]);
//upload file and data object of user
$scope.uploadfile = function() {
        var file = $scope.Image;
         console.dir(file);
        var uploadUrl ="http://localhost:8000/auditconfig/images/"+file.name; 
        fileUpload.uploadFileToUrl(file, uploadUrl); // error here "failed to post"


var user = {
              name: $scope.name,
              lastname: $scope.lastname,
              image:file.name 
             };
$http.post(url+"/add", user) //The user is added to the database
.success(function(data) {
      $scope.ListUsers = data;
}).error(function(err, data) {
    console.log("error: " +data);
});
  };

-After a test of the "uploadfile ()", I get the following results:

//**console.dir(file);
*File:
lastModified:1490260924299
lastModifiedDate; Thu Mar 23 2017 10:22:04 GMT+0100 (Paris, Madrid)
name:"01.png"
size:1637
type:"image/png"
webkitRelativePath:""
__proto__:File

-Test of upload file:

//**console.log('failed to post: ', e);
Failed to load resource: the server responded with a status of 500 (Internal Server Error) :8099/AuditConf/images/01.png
failed to post: Object
Config:Objectd
ata:FormData
__proto__:FormData 
headers:Object
Accept:"application/json, text/plain, */*"
Content-Type:undefined
__proto__:Object
method:"POST"
transformRequest:function identity($)
transformResponse:Array(1)
url:"http://localhost:8099/AuditConf/images/Exception--JAX-RS.png"
__proto__:Object
data:Object
error:"Internal Server Error"
exception:"java.lang.RuntimeException"
message:"java.io.IOException: UT000036: Connection terminated parsing multipart data"
path:"/auditconfig/images/Exception--JAX-RS.png"
status:500
timestamp:1490778930961
__proto__:Object
headers:function (name)
status:500 statusText
:"Internal Server Error"
__proto__;Object
emile01
  • 89
  • 1
  • 3
  • 15
  • You don't have to append 'file' every time with the same key for multiple files, the receiving controller would accept multiple `Http Posted files` withing a single object. – Sajal Mar 29 '17 at 10:17
  • How can I fix this? thank you –  emile01 Mar 29 '17 at 10:22

2 Answers2

1

The solution is:

var app = angular.module('Mainapp', ['ngRoute','file-model','ui.bootstrap']);
app.directive('fileModel', ['$parse', function ($parse) {
    return {
       restrict: 'A',
       link: function(scope, element, attrs) {
          var model = $parse(attrs.fileModel);
          var modelSetter = model.assign;

          element.bind('change', function(){
             scope.$apply(function(){
                modelSetter(scope, element[0].files[0]);
             });
          });
       }
    };
 }]);
this.uploadFileToUrl = function(file, uploadUrl){
    var data = new FormData();
    data.append('file', file);
    return $http.post(uploadUrl, data, {
        transformRequest: angular.identity,
        headers: { 'Content-Type': undefined }
      }).then(function (results) {
        return results;
    });
}
//upload file and data object of user
$scope.uploadfile = function() {
        var file = $scope.Image;
         console.dir(file);

      //URL of API not path of floder
        var uploadUrl ="http://localhost:8000/auditconfig/UpFile"; 
        fileUpload.uploadFileToUrl(file, uploadUrl); 
var user = {
              name: $scope.name,
              lastname: $scope.lastname,
              image:file.name 
             };
$http.post(url+"/add", user) 
.success(function(data) {
      $scope.ListUsers = data;
}).error(function(err, data) {
    console.log("error: " +data);
});
  };
emile01
  • 89
  • 1
  • 3
  • 15
0

Try this:

this.uploadFileToUrl = function(file, uploadUrl){
    var data = new FormData();
    data.append('file', file);

    //Comment below
    //angular.forEach(file, function(file) {
    //  fd.append('file', file);
    //});

    return $http.post(uploadUrl, data, {
        transformRequest: angular.identity,
        headers: { 'Content-Type': undefined }
      }).then(function (results) {
        return results;
    });
}

See the answers here which accepts multiple files within one object 'file'.

Community
  • 1
  • 1
Sajal
  • 4,359
  • 1
  • 19
  • 39
  • After the modification of the code, I have the following error: status 404. I think the problem comes from the url. I did a url test to display an image exists in the server (folder "images"). So I have the image displayed on the browser. link of error: https://codeshare.io/GqAYVB –  emile01 Mar 29 '17 at 10:50
  • so is it uploading the file? 'uploadUrl' should be the api url and not the images path. – Sajal Mar 29 '17 at 11:22
  • Exactly, I'll see how to do the upload API. Thank you –  emile01 Mar 29 '17 at 12:41