5

I am using ajax and rest web service to upload files to the server. I have captured the file upload event and got the file object in my jquery method. I have to send the file object to web service so that i can save the file to db. Here is my jquery code..

  $scope.selectFile = function (fileObj) {
     if(fileObj!=undefined){
        $.ajax({
            url : "/RestServices/services/uploadFile",
            type : "POST",
            data : fileObj,
            processData: false,
            contentType: false,
            success : function(result) {
                $scope.$apply();
            },
            error : function(xhr, tStatus, err) {
                // alert(err);
            }
        });
     }

I have tried using FormData also, but I couldn't get the file in web service.

    var formData = new FormData(); 
    formData.append("fileToUpload", fileObj);   

     if(fileObj!=undefined){
        $.ajax({
            url : "/RestServices/services/uploadFile",
            type : "POST",
            data : formData,
            processData: false,
            contentType: false,
            success : function(result) {
                $scope.$apply();
            },
            error : function(xhr, tStatus, err) {
                // alert(err);
            }

        });

Here is my java code in service

@POST
@Path("/uploadFile")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public void uploadFile(File formData) {     
try {
        System.out.println(formData.getFileName());             
   } catch (Exception e) {
    LOGGER.error("Exception in Upload File Endpoint"+ e.getMessage());
}   
}

If I send file Object directly without using formData, i am getting "media type not supported error" and if i send formData to service, i am getting temporary file only. What datatype should be there in ajax and in service methods? How can I get the uploaded file in the service? Any help will be appreciated.

3 Answers 3

2

I stepped upon this problem today, and I solved it like this:

HTML

 <input type="button" value="Upload document" class="btn btn-xs btn-primary uploadDocumentOnboarding">
 <input id="file" type="file" class="findDocumentOnboarding">

Ajax/Jquery

$(".uploadDocumentGeneral").on("click", function (evt) {

var documentData = new FormData();
documentData.append('file', $('input#file.findDocumentOnboarding')[0].files[0]);
$.ajax({
    url: url,
    type: 'POST',
    data: documentData,
    cache: false,
    contentType: false,
    processData: false,
    success: function (response) {
        alert("Document uploaded successfully.");
    }
});

return false;

});

JAVA

@POST
@Path("upload/{id}")
@Consumes({"application/x-www-form-urlencoded", "multipart/form-data"})

public void addBlob(@PathParam("id") Integer id, @FormDataParam("file") InputStream uploadedInputStream) throws IOException {
    E24ClientTemp entityToMerge = find(id);
    try {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int read = 0;
        byte[] bytes = new byte[1024];
        while ((read = uploadedInputStream.read(bytes)) != -1) {
            out.write(bytes, 0, read);
        }
        entityToMerge.setTestBlob(out.toByteArray());
        super.edit(entityToMerge);
    }
    catch (IOException e) {
        e.printStackTrace();
    }
}

I know it's a little late but I saw the question didn't have an answer yet.

Sign up to request clarification or add additional context in comments.

Comments

0

The method of uploading a file is really different than just an ajax request. Additionally, it is really hard to consider all the old browsers. Fortunately, other people have solved this problem for us.

I recommend using a plugin for jQuery like jQuery File Upload, or use Dropzone, which is totally awesome.

Comments

0

I have it working this way:

//JAVASCRIPT

    var objFile = $jQuery("#fileToUpload");
    var file = objFile[0].files[0];
    API.call({
        url : "rest-url/upload",
        type : "POST",
        contentType : "multipart/form-data",
        data: file,
        processData: false
    }); 

//JAVA

@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_JSON)
@Path("rest-url/upload")
public Response upload(InputStream fileInputStream) throws Exception {
    //here you got your file
    return Response.ok().entity(new Object("response")).build();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.