-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";
}
4

1 回答 1

-4

Ajax 无法处理文件上传。这是因为 javascript 具有阻止访问用户文件系统的安全限制。这是一件好事——您不希望您访问的网站检查您的文件。

您可以通过将表单的目标属性设置为页面上其他地方的不可见 iframe 进行常规表单发布来伪造 ajax 上传。这使用户觉得页面没有重新加载。有一些 javascript 库可以为您执行此操作,例如uploadify

另请参阅此问题

于 2013-06-04T19:16:42.253 回答