How to use multipart to upload a file using XMLHttpRequest?

That's what I'm 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 on the server side I get org.apache.commons.fileupload.FileUploadException: the request was rejected because no multipart boundary was found

Where am I mistaken?

After reading the answer from Aticus, here's what I did, and the file is 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 get the values ​​from the servlet to do some kind of validation other than JSON?

+3
source share
2 answers

Prior to the upcoming version of XMLHttpRequest version 2, you cannot upload a file using Ajax.

Most modern users downloaded by Ajax use <iframe>hack. It uses JS code to create the invisible <iframe>where the form was copied and submitted synchronously. The parent page will remain unchanged and looks as if it was running asynchronously.

, JS-, / HTML DOM, jQuery. , jQuery-form plugin. <iframe> hack. ,

<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>

servlet, , Servlet 3.0 HttpServletRequest#getParts(), Apache Commons FileUpload ().

JSON .

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));

Ajax-Servlet-JSON .

+1

, . .

, post.

+1

All Articles