java - how to use multipart to upload file using XMLHttpRequest? - Stack Overflow

Here is what I am doingvar url_action="tempSaveConfig";var client; var dataString;if (windo

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.apachemons.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?

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.mons.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?

Share Improve this question edited May 9, 2011 at 8:45 AabinGunz asked May 9, 2011 at 8:34 AabinGunzAabinGunz 12.4k54 gold badges150 silver badges220 bronze badges 2
  • Do you actually send anything? – Thomas Commented May 9, 2011 at 8:38
  • @Thomas: I just want to send the file. Do i need to add these lines? dataString=document.getElementById("tfile").value;client.setRequestHeader("Content-length", dataString.length); client.send(dataString); because this is also giving the same exception. how do I send file using XMLHttpRequest? tfile is the id of input type file – AabinGunz Commented May 9, 2011 at 8:40
Add a ment  | 

2 Answers 2

Reset to default 1

Until the uping 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 patibility and to minimize headaches with regard to writing crossbrowser patible code, I'd strongly remend to grab an existing JS library which excels in handling ajaxical stuff and traversing/manipulating HTML DOM tree, such as jQuery. It es 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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745414730a4626694.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信