簡體   English   中英

如何為Mvc3文件上傳編碼控制器

[英]How to code controller for mvc3 file upload

@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]時如何為圖片上傳編寫控制器或如何在控制器上上傳文件

這是我過去所做的方式(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

您可以僅將模型作為[HttpPost]操作方法中的參數,並讀取fileName屬性。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM