开发者

how to use multipart to upload file using XMLHttpRequest?

Here is what I am doing

var url_action="/temp/SaveConfig";
 var client; 
 var dataString;

 if (window.XMLHttpRequest){ // IE7+, Firefox, Chrome, Opera, Safari
     client=new XMLHttpRequest();
 } else {                    // IE6, IE5
     client=new ActiveXObject("Microsoft.XMLHTTP");
 }

 client.onreadystatechange=function(){

     if(client.readyState==4&&client.status==200)
     {
         alert(client.responseText);

     }
 };

 //dataString=document.getElementById("tfile").value;
 client.open("POST",url_action,true);
 client.setRequestHeader("Content-type", "multipart/form-data"); 
 client.setRequestHeader("Connection", "close");     
 client.send();

But at the server side i get org.apache.commons.fileupload.FileUploadException: the request was rejected because no multipart boundary was found

Where am i going wrong?

After reading reply from Aticus Here is what i did and file is getting uploaded.

var form=document.forms["mainForm"];

 form.setAttribute("target","micox-temp");
 form.setAttribute("action",url_action);开发者_开发知识库
 form.setAttribute("method","post");
 form.setAttribute("enctype","multipart/form-data");
 form.setAttribute("encoding","multipart/form-data");
 form.submit();

but now how do i recieve values from servlet to perform some kind of checking apart from JSON?


Until the upcoming XMLHttpRequest version 2, you cannot upload a file using Ajax.

Most of the current Ajaxbased file uploaders use an <iframe> hack. It uses JS code to create an invisible <iframe> where the form is been copied in and is been submitted synchronously. The parent page will just stay unchanged and it looks like as if it is been done asynchronously.

To get best crossbrowser compatibility and to minimize headaches with regard to writing crossbrowser compatible code, I'd strongly recommend to grab an existing JS library which excels in handling ajaxical stuff and traversing/manipulating HTML DOM tree, such as jQuery. It comes with plethora of form upload plugins, the simplest one being the jQuery-form plugin. It supports file uploads as well with help of the hidden <iframe> hack. It's then basically as easy as

<script src="jquery.js"></script>
<script src="jquery-form.js"></script>
<script>
    $(document).ready(function() {
        $('#formid').ajaxForm(function(data) {
            // Do something with response.
            $('#result').text(data.result);
        });
    });
</script>
...
<form id="formid" action="upload" method="post" enctype="multipart/form-data">
    <input type="file" name="file" />
    <input type="submit" />
</form>
<div id="result"></div>

In the server side, just have a servlet which processes the request the usual way, either with the Servlet 3.0 provided HttpServletRequest#getParts() or with the good old Apache Commons FileUpload (examples here).

Either way, you can just return the response as JSON the usual way

Map<String, Object> data = new HashMap<String, Object>();
data.put("result", "Upload successful!");
// ...
response.setContentType("application/json");
resposne.setCharacterEncoding("UTF-8");
resposne.getWriter().write(new Gson().toJson(data));

For more Ajax-Servlet-JSON examples, check this answer.


Files are not transmittable via asynchronous requests such as this. You'll need to submit it in a multipart form.

Depending on what the file is you could store the data in a post variable.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜