How to send a csv file through xhrPost()?

410 views Asked by At

Currently, my form element looks like below:

<form enctype="multipart/form-data" name="copyReplaceForm" method="POST" action="/app/applications/copyreplace/postCsv">

But instead of giving the action, enctype and method on the <form>, I want to send it using dojo.xhrPost().

Could someone please tell me how to send using xhrPost?

Also, my REST code piece looks like below:

@POST
@Path("/bulkCopyReplaceFirst")
@Produces(MediaType.TEXT_PLAIN)
@Consumes(MediaType.MULTIPART_FORM_DATA)

My xhrPost looks like below

var result;
dojo.xhrPost({
        url :"/CopyReplace/bulkCopyR",
        preventCache: true,
        contentType : "multipart/form-data",
        load: function(response) {
                txtResponse = response;
                console.log("response is : txtResponse"+txtResponse)
        },
        error: function(error, ioArgs) {
                console.log("postImageOptions() ERROR :: " + error);
                console.log("postImageOptions() ioArgs :: " + ioArgs);
                return error;
        }


    });
}
2

There are 2 answers

1
Ferry Kranenburg On

The url in the xhrPost and the path specified in @Path annotation are not the same.

You should add a form property to the xhrPost.

var result;
dojo.xhrPost({
        url :"/bulkCopyReplaceFirst",
        form: document.forms["copyReplaceForm"],
        load: function(response) {
                txtResponse = response;
                console.log("response is : txtResponse"+txtResponse)
        },
        error: function(error, ioArgs) {
                console.log("postImageOptions() ERROR :: " + error);
                console.log("postImageOptions() ioArgs :: " + ioArgs);
                return error;
        }


    });
}
0
Stefano On

You can directly use the Dojo Uploader.

var up = new Uploader({
            label: "Upload csv",
            multiple: false,       // true if you can upload more files
            uploadOnSelect: false,   // true if you want to upload without clicking on the submit of the from
            url: "/path/name.csv",   // the route path to the backend (xhr url)
            style: "",
            onBegin: function() {
               // start of upload
            },
            onProgress: function(rev) {
               // uploading...
            },
            onChange: function() {
               // on file change
               var file = up.getFileList();
             }
         }, this.domNode);