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" />
}
This is what I have so far, here is what my model looks like:
public class PictureUpload
{
public HttpPostedFile fileName { get; set; }
public MetaTags MetaTagsObj { get; set; }
}
I am not sure how to write my controller for the picture upload or how to upload the file at the controller when I do a [HttpPost]
Here is how I have done it in the past (asp.net mvc 2)... There may very well be a much easier way to do it with .net 4 and 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() is an extension method defined like:
public static class HttpPostedFileBaseExtensions
{
public static bool HasFile(this HttpPostedFileBase file)
{
return (file != null && file.ContentLength > 0);
}
}
enter code here
You can just take your model as a parameter in the [HttpPost]
action method and read the fileName
property.
精彩评论