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?

AabinGunz
  • 12,109
  • 54
  • 146
  • 218
  • Do you actually send anything? – Thomas May 09 '11 at 08: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 May 09 '11 at 08:40

2 Answers2

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.

Atticus
  • 6,585
  • 10
  • 35
  • 57
  • @Atticus: Thanks for your reply, I updated my code section kindly take a look. :) – AabinGunz May 09 '11 at 08:47
  • wait... you successfully ajax'd a file? or did you postback – Atticus May 09 '11 at 08:48
  • @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. – AabinGunz May 09 '11 at 08:51
  • @Atticus: how can i recieve values from servlet to perform some kind of checking apart from JSON? – AabinGunz May 09 '11 at 09:49
  • 1
    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. – Atticus May 09 '11 at 09:52
  • @Atticus: I used `PrintWriter` to echo and it gets printed on the page, instead how will i get the value in a variable and comapre it with some string? – AabinGunz May 09 '11 at 10:05
  • oh -- right disregard that, i thought you were talking about an ajax request... Just store $returnVar = $_POST['post-key-name']; and return the variable to your page, access it how you normally access a php variable. – Atticus May 09 '11 at 10:06
  • @Atticus: I am new to web developing, I have never tried php, supposing in my servlet i use `PrintWriter` to send back some text, then how can i receive it in javascript? sorry for so much of trouble :) – AabinGunz May 09 '11 at 10:37
  • @Atticus: please get back whenever you have some free time. Thanks – AabinGunz May 09 '11 at 11:58
  • 1
    you don't print results to the page, you pass them to the page as variables. read some articles on this – Atticus May 09 '11 at 12:01
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.

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • 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 :) – AabinGunz May 10 '11 at 06:11