-2

I am trying to submit a form using ajax. Form contains text fields and a file upload field. The problem is that it submits the text but it does not submit files. my form is

<form onsubmit ="return save();"  id="postadform" enctype="multipart/form-data">
Name<input type ="text" name ="name" />
Upload image <input type="file" name="image" id ="filee"/>
<input type ="submit" value = "submit" />
</form>

<script src="~/Scripts/jquery-1.7.1.js"></script>
    <script type="text/javascript">
        function save() {
            $.ajax({
                type: 'POST', url: '/Home/saveData', data: $('#postadform').serialize(),enctype:"multipart/form-data",
                success: function (x) {
                   //do what ever you want
                },
                error: function () {
                    alert('There is some error, plz try again!');
                }
            });

            return false;
        }

        </script>

And this is part of the HomeController.cs file:

[HttpPost]
public String saveData()
{
    String name = Request["name"];
    String filename =  Request.Files[0].FileName; //Problem in this line.  

    return "Successful";
}
pattyd
  • 5,927
  • 11
  • 38
  • 57

1 Answers1

-4

Ajax is not capable of handling file uploads. This is because javascript has security limitations that prevent access to the user's file system. This is a good thing - you don't want websites you visit to check out your files.

You can fake the ajax upload by doing a regular form post with the form's target attribute set to an invisible iframe elsewhere on your page. This makes it appear to the user that the page did not reload. There are javascript libraries available to do this for you, such as uploadify.

See also this question.

Community
  • 1
  • 1
Tap
  • 6,332
  • 3
  • 22
  • 25
  • 1
    This is not entirely correct, and is, unfortunately recited often on SO. Any browser that supports the File API can upload files via XHR level 2. – Ray Nicholus Jun 04 '13 at 20:12
  • The misundertanding here is the filechooser inputfield cannot select files without explicit user input (i.e. cannot select by JS). – laffuste Jun 26 '14 at 02:54