0

I have javaee project. I want to send image file to my servlet via ajax. Ajax not sending image file to my java class. But it is sending textarea value. Here is my form

<form enctype="multipart/form-data" beanclass="ActionBean">
    <input type="file" id="uploadFile" name="newAttachment"/>
    <textarea name="name" id="name" rows="2" cols="30"></textarea>
    <s:submit value="Edit" name="saveOfferInfo" onclick="return edit(this);" />

JavaScript function:

function edit(button) {
    var form = button.form;
    var params = $(form).serializeArray();
    params.push({name: '_eventName', value: button.name});
    $.post(form.action, params, function (data) {
        alert("success");
});
Khalid Farhan
  • 435
  • 1
  • 3
  • 19
sj_8
  • 173
  • 1
  • 16

2 Answers2

0

File upload is not possible using AJAX, check for further details

First of all I have to say that to create a pure AJAX file upload system is not possible because of security limitations of JavaScript. All of the Ajax upload systems I know use some third party tool/package or only mimics the AJAX feeling. Even so it makes file upload process a bit nicer. In the next section I will present you a solution which imitates the AJAX process, but uses a normal upload process and iFrames.

The concept:

  • Create a simple HTML form for file upload
  • Set the target to an iFrame which is on the actual page but not visible
  • Call a JavaScript function on form submit to display the animation
  • After the PHP part finishes the upload process, then it hides the animation

Read more

If you don't bother about older browser versions and want to code for the latest browsers then you can use FileReader API See Using HTML5 file uploads with AJAX and jQuery

Community
  • 1
  • 1
Rohan Kumar
  • 40,431
  • 11
  • 76
  • 106
0

Looking at the doc of $.serializeArray(), it specifically says that

Data from file select elements is not serialized.

Unfortunately, uploading file in AJAX isn't as straight forward. There is a detailed tutorial here using straight-up JQuery. The gist of it is that you need to:

  1. Bind the file input to a change event handler,
  2. Gather all the form data in a FormData object,
  3. Then POST the form data using the $.ajax function.

Too much work?

Alternately, if you don't mind including plugins in your codes, here are some options:

  1. jQuery-Ajax-File-Upload
  2. jquery-form

Or as Rohan pointed out, if you are using HTML5, you can explore the FileReader API.

ivan.sim
  • 8,972
  • 8
  • 47
  • 63