0

im using this code to upload file to my REST API, and it works fine , this is my form :

<form action="webresources/documents/upload" 
      method="post" 
      enctype="multipart/form-data">

    <p>
        Select a file : 
        <input type="file" name="file" size="45" />
    </p>
    <input type="submit" value="Upload" />

</form>

and this is my REST API :

@POST
    @Path("/upload")
    @Consumes(MediaType.MULTIPART_FORM_DATA)
    public Response uploadFile(@MultipartForm Document document) {
.....
}

my question is: how to send the same request using angularjs instead of using action="webresources/documents/upload" on my form.

Michael Markidis
  • 4,163
  • 1
  • 14
  • 21
James
  • 1,190
  • 5
  • 27
  • 52
  • This code has nothing related to angular. As such, I would like to remind you that SO is not here to write code for you. Do some research, write some angular code, and come back to us when you have a specific problem. – rmlan Jun 20 '16 at 21:22
  • I think he's asking how to upload a file using AngularJS. It's not completely irrelevant. – kensplanet Jun 20 '16 at 21:27
  • Hi @Michael Markidis , thank you for your response, if you read my question , you will find it clear and i have a specific issue , i'm asking on how i can upload my file using angular , without calling my REST API in the form action ="" , but please try to understand people before attacking them,regards – James Jun 20 '16 at 23:35

1 Answers1

0

You don't require a form tag,

This is how your HTML would look like,

 <p>
        Select a file : 
        <input type="file" name="file" size="45" />
    </p>
<button ng-click="upload()">Upload</button>

Your controller code would be something like this,

$scope.upload = function () {
  var fd = new FormData();
  fd.append('file', file);

  $http({
    url: 'webresources/documents/upload',
    data: fd,
    method: "POST",
    headers: {
      "Content-Type": undefined
    }
  });
}

This will upload your file to the server without form tags.

kensplanet
  • 493
  • 8
  • 15
  • Hi @Kensplanet, thank you for the response , but i got an error "ReferenceError: file is not defined" , please where is the declaration of variable file? – James Jun 21 '16 at 00:16
  • You will have to implement the logic as per this Stackoverflow answer - http://stackoverflow.com/questions/17922557/angularjs-how-to-check-for-changes-in-file-input-fields – kensplanet Jun 21 '16 at 15:16