【问题标题】:asp.net mvc 4 upload file using ajax form helperasp.net mvc 4 使用 ajax 表单助手上传文件
【发布时间】:2013-02-21 04:50:53
【问题描述】:

我正在使用 ajax 表单将多个文件上传到服务器。这就是我的表单的样子

   @using (@Ajax.BeginForm("SaveProjectSummary", "Project", new { id = Model.ProjectId }, new AjaxOptions { OnSuccess = "Add_OnCompleteSummarySave()" }, new { enctype = "multipart/form-data" }))

我可以这样做,但我无法在服务器上的 Request.Files 中找到任何内容。只是想确定我是否使用了这个对我来说似乎没有的权利,所以任何帮助都将不胜感激。

【问题讨论】:

    标签: jquery asp.net asp.net-mvc asp.net-mvc-3 asp.net-mvc-4


    【解决方案1】:

    很遗憾,Ajax.BeginForm 不能用于上传文件。

    • 有uploadify之类的插件

    http://www.uploadify.com/forum/#/discussion/1685/uploadify-and-ajax/p1

    • 或者这个 jquery 插件

    http://malsup.com/jquery/form/

    【讨论】:

    • @afr0,普通的 Html.BeginForm 可以做到。但是有 AJAX 方法。检查我修改后的答案以获取一些替代方案。
    • 我不想包含 swf。
    【解决方案2】:

    另一个很棒的上传组件是 PlUpload

    http://www.plupload.com/

    确实如此:

    • chucked 文件上传器,因此您可以上传大文件。例如。 100Mb
    • 客户端文件缩放
    • 拖放文件选择

    仅供参考,.NET 中用于处理来自 PlUpload 的发布请求的服务器端代码:

    var chunk = Request.Form["chunk"] != null ? int.Parse(Request.Form["chunk"]) : 0;
    
    var fileName = Request.Form["name"] ?? "";
    
    //open a file, if our chunk is 1 or more, we should be appending to an existing file, otherwise create a new file
    var fs = new FileStream(Server.MapPath("/files/" + fileName), chunk == 0 ? FileMode.OpenOrCreate : FileMode.Append);
    
    //write our input stream to a buffer
    var buffer = new Byte[Request.Files[0].InputStream.Length];
    Request.Files[0].InputStream.Read(buffer, 0, buffer.Length);
    
    //write the buffer to a file.
    fs.Write(buffer, 0, buffer.Length);
    fs.Close();
    

    如果您热衷于推出自己的组件,请查看现代浏览器上可用的文件系统 API。它允许您获取文件内容二进制文件并使用 AJAX 调用上传

    【讨论】:

    • 非常有趣。想试驾这个。
    • 我用它为geolocation.ws上传图片看看它是如何工作的
    • @MaksymKozlenko 它可以与 asp.net mvc ajax 表单助手一起使用吗?
    • @afr0: 否。PlUpload 客户端代码使用图像数据发出 AJAX 请求。
    【解决方案3】:

    [HttpPost] 公共 JsonResult UploadImage(HttpPostedFileWrapper imageFile) {

            if (imageFile == null || imageFile.ContentLength == 0 || imageFile.ContentLength > 205168)
            {
    
                return new JsonResult
                {
                    ContentType = "text/html",
                    Data = "No file was uploaded."
    
                };
            }
    
            if (imageFile == null || imageFile.ContentLength == 0 || (imageFile.ContentType != "image/png" && imageFile.ContentType != "image/jpg" && imageFile.ContentType != "image/jpeg" && imageFile.ContentType != "image/pjpeg"))
            {
                return new JsonResult
                {
                    ContentType = "text/html",
                    Data = "Type"
                };
            }
            if (Session["CityId"] != null)
            {
                if (MdlNadal == null)
                {
                    MdlNadal = new mdlNadal();
                }
                string strFilePaths = "";
    
                int CityId = Convert.ToInt32(Session["CityId"].ToString());
                string strCityName = "";
                if (Session["CityName"] != null)
                {
                    strCityName = Session["CityName"].ToString();
                }
    
                string strFileNames = imageFile.FileName.Replace(@"\", "/");
                string imgPath = ConfigurationManager.AppSettings["ImagePath"].ToString().Replace("~", "");
                strFileNames = strFileNames.Split('/')[strFileNames.Split('/').Length - 1];
                Session["ImageName"] = strFileNames;
                ViewBag.ImageName = strFileNames;
                strFilePaths = Request.Url.Scheme + "://" + Request.Url.Authority + imgPath + strCityName + "" + CityId + "/" + strFileNames;
                MdlNadal.UpdateCityImageByCityID(CityId, strFilePaths);
                if (imageFile != null)
                {
                    if (!Directory.Exists(Server.MapPath(Url.Content(ConfigurationManager.AppSettings["ImagePath"].ToString() + strCityName + "" + CityId))))
                    {
                        Directory.CreateDirectory(Server.MapPath(Url.Content(ConfigurationManager.AppSettings["ImagePath"].ToString() + strCityName + "" + CityId)));
                    }
                    else
                    {
                        int counts = Directory.GetFiles(Server.MapPath(Url.Content(ConfigurationManager.AppSettings["ImagePath"].ToString() + strCityName + "" + CityId))).Count();
                        if (counts > 1)
                        {
                            string[] StrArr = Directory.GetFiles(Server.MapPath(Url.Content(ConfigurationManager.AppSettings["ImagePath"].ToString() + strCityName + "" + CityId)));
                            for (int i = 0; i <= counts - 1; i++)
                            {
                                string strFileNameCheck = StrArr[i];
                                //strFileNameCheck = strFileNameCheck.Replace(@"\", "/");
                                //strFileNameCheck = strFileNameCheck.Split('/')[strFileNameCheck.Split('/').Length - 1];
                                try
                                {
                                    System.IO.File.Delete(strFileNameCheck);
                                }
                                catch (Exception ex)
                                {
                                    throw ex;
                                }
    
                            }
                        }
                    }
                    var FilePath = Path.Combine(Server.MapPath(Url.Content(ConfigurationManager.AppSettings["ImagePath"].ToString() + strCityName + "" + CityId)), strFileNames);
                    imageFile.SaveAs(FilePath);
                }
    
            }
    
            return new JsonResult
            {
                ContentType = "text/html",
                Data = "Save"
    
            };
        }
    

    @using (Html.BeginForm("UploadImage", "Nadal", FormMethod.Post, 新的 { enctype = "multipart/form-data", id = "mws-验证", 目标 = "上传目标", @class= "mws 形式" })) {

                        <label class="title10">
                            <strong>Choose a background for this city</strong>
                        </label>                                             
                        <div class="mws-form-item large">
                            <input type="file" name="imageFile" id="imageFile" onchange="return SetAttachFlag();" />
                            (Supported File Types : .jpg, .jpeg, .png) (Maximum Size: 200 Kb)
                            <iframe id="UploadTarget" name="UploadTarget" onload="UploadImage_Complete();" style="position: absolute;
                                left: -999em; top: -999em;"></iframe>
                        </div>
    
                    }
    

    【讨论】:

    • 我不想使用 BeginForm 那是你代码的唯一问题
    • 顺便说一句,您不必使用 iframe 从 BeginForm 发布图像。
    【解决方案4】:

    为什么不利用 HTML5 中的文件 API。查看这些链接,为您指明正确的方向。

    http://www.html5rocks.com/en/tutorials/file/dndfiles/

    http://timothypoon.com/blog/2011/05/10/ajax-uploading-with-html5s-file-api/

    【讨论】:

    • 我真的很喜欢 HTML5 文件 API,并试了一下,它适用于 chrome 和 FF,但我使用的 IE9 不支持这些 API,这对他们正在使用的 MS 来说真的很糟糕这种浏览器的开源方向..只有一些天才才能想出这个想法
    • 我确实使用 Html.BeginForm 实现了将多个文件发送到服务器,但它需要将整个表单连同文件一起提交,这破坏了我所有的用户体验,所以我认为现在 jquery 是我的最后赌注
    猜你喜欢
    • 2013-01-28
    • 2012-07-27
    • 1970-01-01
    • 2013-12-23
    • 2012-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-12
    相关资源
    最近更新 更多