【问题标题】:How to code controller for mvc3 file upload如何为 mvc3 文件上传编写控制器代码
【发布时间】:2011-05-18 02:28:42
【问题描述】:
@model Framely2011.Models.PictureUpload

@{
    ViewBag.Title = "Upload";
}

<h2>Upload</h2>

@using (Html.BeginForm("Upload", "Member", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <input type="file" name="myFile" id="myFile" />

    @Html.TextBoxFor(x => x.MetaTagsObj.Meta1)<br />
    @Html.TextBoxFor(x => x.MetaTagsObj.Meta2)<br />
    @Html.TextBoxFor(x => x.MetaTagsObj.Meta3)<br />

    <input type="submit" value="submit" />
}

这是我目前所拥有的,这是我的模型的样子:

public class PictureUpload
    {
        public HttpPostedFile fileName { get; set; }
        public MetaTags MetaTagsObj { get; set; }
    }

当我执行[HttpPost]时,我不确定如何编写我的控制器以上传图片或如​​何在控制器上上传文件

【问题讨论】:

    标签: c# asp.net asp.net-mvc-3 razor


    【解决方案1】:

    这是我过去的做法(asp.net mvc 2)... 使用 .net 4 和 asp.net mvc 3 可能有更简单的方法

    foreach (string upload in Request.Files)
                {
                    if (!Request.Files[upload].HasFile()) continue;
    
                    string mimeType = Request.Files[upload].ContentType;
                    Stream fileStream = Request.Files[upload].InputStream;
                    string fileName = Path.GetFileName(Request.Files[upload].FileName);
                    int fileLength = Request.Files[upload].ContentLength;
                    byte[] fileData = new byte[fileLength];
                    fileStream.Read(fileData, 0, fileLength);
                    //do something with the byte array (filedata)
                }
    

    HasFile() 是一个扩展方法,定义如下:

    public static class HttpPostedFileBaseExtensions
    {
        public static bool HasFile(this HttpPostedFileBase file)
        {
            return (file != null && file.ContentLength > 0);
        }
    }
    
    enter code here
    

    【讨论】:

    • 没有理由写x ? true : false
    • 大声笑,你是对的......我从博客上得到了代码,显然没有仔细查看它:# Fixed
    【解决方案2】:

    您可以将您的模型作为[HttpPost] 操作方法中的参数并读取fileName 属性。

    【讨论】:

      猜你喜欢
      • 2012-12-18
      • 2015-06-28
      • 1970-01-01
      • 2021-10-20
      • 2014-12-20
      • 1970-01-01
      • 1970-01-01
      • 2018-07-10
      相关资源
      最近更新 更多