简体   繁体   中英

How to send file in chunks using Ajax post request to Java Eclipse rest service

I am implementing PDF file upload functionality in my web application where I am trying to read file in javascript and dividing it in chunks using file.slice(start, stop), after reading this I am trying to send it in Ajax post request using loop till all chunks are send to service and like shown below

self.ajaxCallToUploadFile = function (docId, finalChunk, fileName, data) {
    var formData = new FormData();
    formData.append('file', data);

    var serviceUrl = "http://localhost:8080/JerseyDemos/rest/upload/pdf/docId/finalChunk/FileName";

    return $.ajax({
        url: serviceUrl,
        type: 'POST',
        success: function (rdata) {
            alert(rdata.d);
        },
        error: function (errorData) {                    
            alert(errorData.responseText);
        },
        data: formData,
        cache: false,               
        contentType: 'multipart/form-data',
        //contentType: false,
        processData: false,
        async: false
    });
};

With file chunk as data I am sending other parameters in query string in service URL. I am new to Java and Java services, I am using Eclipse to write services. I tried to read this file chunk as Inputstream but it fails. I tried to search for specific answer on this question but everywhere I am getting answer to how to send file from java code to java service. Here I am expecting answer on how to should send it from javascript to Java rest service and how to read it in Java rest service.

Please help me on this as i am struggling to implement this functionality below is the Java rest service method decoration I tried with.

 @Path("/upload")
public class JerseyService {
    @POST
    @Path("/pdf/{docId}/{chunkNumber}/{finalChunk}")
    @Consumes({ MediaType.MULTIPART_FORM_DATA})
    public Response uploadPdfFile(@PathParam("docSetId") final Integer docId,
            @PathParam("chunkNumber") final Integer chunkNumber, @PathParam("finalChunk") final Boolean finalChunk,
            @FormDataParam("file") FormDataBodyPart file)

You have some error in your javascript ajax url

looking at serviceUrl http://localhost:8080/JerseyDemos/rest/upload/pdf/docId/finalChunk/FileName there is a mismatch in the expected types of your java Rest Service (RS) parameters and your javascript url:

  • docId is a String in your URL, yet in your Java RS, it is marked as Integer and its called docSetId .

  • your java RS ist expecting some types: docId -> Integer , chunkNumber-> Integer , finalChunk -> Boolean . Yet you are sending only Strings as url (docId/finalChunk/FileName).

The java RS mapper can not locate your rest service method to order your request. Just fix your URL. As Example try:

serviceUrl = "http://localhost:8080/JerseyDemos/rest/upload/pdf/203/4/myFileName"

EDIT :

if your parameters are ok, please check that your browser really sends your data chunks to the server. It can send your other (text) parameters (docId, chunkNumber,and finalchunk), but having trouble sending your binary data. You can check that by using firebug (if you are testing with mozilla) see how to . Monitor each upload you send to see if they actually leave your browser. Inspect your request to see if a data chunk also leaves, and which name it bears.

if it doesn't leave your browser, or leave but is not well formed, then the problem is on the client side (your javascript slice and appending code is at fault here).

if however it leaves your browser, then try to process the chunk using InputStream like this:

@Path("/upload")
public class JerseyService {
       @POST
       @Path("/pdf/{docId}/{chunkNumber}/{finalChunk}")
       @Consumes({ MediaType.MULTIPART_FORM_DATA})
       public Response uploadPdfFile(@PathParam("docSetId") final Integer docId,
       @PathParam("chunkNumber") final Integer chunkNumber, 
       @PathParam("finalChunk") final Boolean finalChunk,
       @FormDataParam("file") InputStream  file){

             // do something with file like 
             int nextByte = -1;
             while((nextByte  = file.read()) != -1){
             // process your byte here
           }

       }

     }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM