3

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?

2
  • Do you actually send anything? 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 Commented May 9, 2011 at 8:40

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I passed a string with variables separated with a delimiter , and used splitOutput=client.responseText.split(","); to store values as variables for checking. This solved my problem. In future I'll try to work on Json and take your method into consideration. Thanks for your help :)
1

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.

10 Comments

@Atticus: Thanks for your reply, I updated my code section kindly take a look. :)
wait... you successfully ajax'd a file? or did you postback
@atticus: I did not get you, I simply used a variable out of form's id present on the html file and using that form's variable submitted the form.
you can have the server echo a single integer, it doesn't have to be JSON, but it should be json -- encoding is a much safer route.
you don't print results to the page, you pass them to the page as variables. read some articles on this
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.