如何将图像文件和一些数据从Ajax传递到MVC控制器

时间:2016-03-16 10:33:24

标签: jquery ajax asp.net-mvc

我有部分视图来显示图像上传按钮和照片列表,如下所示:

<input type="file" id="FileUpload" multiple />
<input type="submit" id="Upload" value="Upload" />

<table class="table">

<!-- A table goes here to view the images from a table in the database using @foreach as below where Model is a list of images obtained from the database: -->

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.cover)
        </td>
        <td>
            @Html.Image("/Images/" + item.id_product + "/" + item.id_product + ".jpg", "Image", "50")
            @Html.DisplayFor(modelItem => item.Product.type)
        </td>
    </tr>
}
</table>


<script>
    $(document).ready(function () {
        $("#Upload").click(function () {
            var formData = new FormData();
            var totalFiles = document.getElementById("FileUpload").files.length;
            for (var i = 0; i < totalFiles; i++)
            {
                var file = document.getElementById("FileUpload").files[i];

                formData.append("FileUpload", file);
            }
            $.ajax({
                type: "POST",
                url: '/Products/Upload',
                data: formData,
                dataType: 'json',
                contentType: false,
                processData: false,
                success: function (response) {
                    alert('succes!!');
                },
                error: function (error) {
                    alert("errror");
                }
            });
        });
    });

</script>

我应该接收上传文件的控制器操作如下:

[HttpPost]
        public void Upload()
        {
            for (int i = 0; i < Request.Files.Count; i++)
            {
                var file = Request.Files[i];
                var fileName = Path.GetFileName(file.FileName);
                var path = Server.MapPath("~/Images/");
                if(this.CreateFolderIfNeeded(path))
                    file.SaveAs(path + fileName);
            }
        }

在主视图中,我有以下内容:

@Ajax.ActionLink("All", "All", "Products", new { id = Model.id_product }, new AjaxOptions()
       {
           HttpMethod = "GET",
           UpdateTargetId = "divImages",
           InsertionMode = InsertionMode.Replace
       })
                <div id="divImages"></div>

上面的all(int id)方法用于返回包含数据库中图像列表的局部视图。

现在,我有以下要求:

用户点击上传按钮后,我想将参数(@Model.Take(1).Single().id_product)传递给控制器​​中的ActionMethod Upload()以保存路径(根据@Model.Take(1).Single().id_product)数据库中上传的图像。

另外我想在图像上传成功后,我想自动刷新局部视图(表格)以查看新上传的图像。

我希望有人可以提供帮助。

1 个答案:

答案 0 :(得分:1)

这是Stephen Muecke的评论。它作为我的问题的答案。我复制并粘贴在这里,以便人们可以看到它:

如果您在<form>标记中包装文件输入和提交按钮,那么您只需使用

var formdata = new FormData($('form').get(0));

然后您可以使用formdata,append(id: 'yourValue');添加其他值并将方法更改为

public void Upload(IEnumerable<HttpPostedFileBase> files, int ID)

并为文件输入name属性 - name="files"

有关其他信息,请参阅this answer

相关问题