Upload file using jQuery and post it to Controller

馋奶兔 提交于 2019-12-13 05:02:48

问题


I'm wondering if it would be possible at all to upload a file by posting it to a controller action in ASP.NET MVC. The dialog for this upload form will be dynamically generated and will be inside a jQuery dialog in my case.

I'm aware of the file input element but I'm not sure how to send the file to a controller action, not sure how to set the action parameter


回答1:


Your action should like this:

[HttpPost]
public ActionResult Upload(HttpPostedFileBase file) {

  if (file.ContentLength > 0) {
    var fileName = Path.GetFileName(file.FileName);
    var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
    file.SaveAs(path);
  }

  return RedirectToAction("Index");
}

Taken from :http://haacked.com/archive/2010/07/16/uploading-files-with-aspnetmvc.aspx/

Then using jQuery Dialog for file upload:

$dialog.dialog("option", "buttons", {
    "Save": function () {
        var dlg = $(this);
        var formData = new FormData($("#" + formName)[0]);
        $.ajax({
            url: /Controller/upload,
            type: 'POST',
            data: formData,
            processData: false, 
            contentType: false,
            success: function (response, textStatus, xhr) {
            ...
                }
            },
            error: function (xhr, status, error) {
                ....
            }
        });
    },
    "Cancel": function () {
        $(this).dialog("close");
        $(this).empty();
    }

});



回答2:


<form id="frmFile" method="post" enctype="multipart/form-data" action="<%=Url.Content("~/WriteSomeServerAction/")%>" >

</form>

//Put this form in modal

and Make Submit event will send file to Action.There you can access file as in Model element as like UploadedFileData .

if (_File.UploadedFileData != null && _File.UploadedFileData.ContentLength > 0)
                {
                    byte[] buffer = new byte[_File.UploadedFileData.ContentLength];
                    _File.UploadedFileData.InputStream.Read(buffer, 0, buffer.Length);
                    _File.FileData = System.Text.Encoding.Default.GetString(buffer);
                    _File.UploadedFileData = null;
                }


来源:https://stackoverflow.com/questions/31071374/upload-file-using-jquery-and-post-it-to-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!