Asp.Net Mvc ajax file upload with partialViews?

2019-05-24 18:29发布

问题:

Is it possible ajax file upload with partial views?

I try to do this with following:

_Upload.cshtml (PartialView)

<script type="text/javascript">
$(document).ready(function () {
    $("#upload").click(function () {
        var val = $("#galeries").val();
        if (val == null || val == "") {
            val = 0;
        }
        var form = $("#form");
        $.ajax({
            url: form.attr('action'),
            type: form.attr('method'),
            data: { galeryId: val, formElements: form.serialize() },
            complete: function () {

            },
            error: function (jqXhr, textStatus, errorThrown) {
                alert("Error '" + jqXhr.status + "' (textStatus: '" + textStatus + "', errorThrown: '" + errorThrown + "')");
            },
            success: function (data) {

            }
        });
    });
});
</script>

@using (Html.BeginForm("_Upload", "Admin", FormMethod.Post, new { enctype = "multipart/form-data", id = "form" }))
{
    <input type="file" name="file" id="file" />
    <input type="button" value="Yükle" id="upload" />
}

CONTROLLER

[HttpPost]
public ActionResult _Upload(IEnumerable<HttpPostedFileBase> files, int galeryId,FormCollection formElements)
{
    foreach (var file in files)
    {
        if (file.ContentLength > 0)
        {
            var fileName = Path.GetFileName(file.FileName);
            var path = Path.Combine(Server.MapPath("~/Images/Galery_" + galeryId), fileName);
            file.SaveAs(path);
        }
    }

    return View();
}

I dont know, Which parameter types, I should pass to controller action. I debugged it with this situation.

galeryId = 1;
formElements = "";
files = null;

If it is possible (ajax file upload with partial views), How Can I do?

Thanks.

回答1:

The serialize approach won't work with file uploads (file input types are ignored). Depending on your target browsers, you can use the FormData approach (for IE it must be 10+), or start playing with iframes to post your form asynchronously.