【问题标题】:Upload file with MVC 4.5 .NET Framework [closed]使用 MVC 4.5 .NET Framework 上传文件 [关闭]
【发布时间】:2014-05-24 08:31:23
【问题描述】:
如何使用带有剃须刀和数据库的 c# MVC 4.5 创建文件上传功能(模型、视图、控制器)的最佳方式?
请把视图和控制器代码放在这里好吗?
【问题讨论】:
标签:
c#
asp.net-mvc
razor
file-upload
upload
【解决方案1】:
我不知道这是否是最好的方法,但它就是这样。如果您不想回发当前页面,则此方法有效。
@using (Html.BeginForm("UploadImage", "User", FormMethod.Post,
new
{
enctype = "multipart/form-data",
id = "ImgForm",
name = "ImgForm",
target = "UploadTarget",
style = "display:none;"
}))
{
<h3>Upload Image</h3>
<input type="file" name="ImageFile" id="ImageFile" />
}
<iframe id="UploadTarget" name="UploadTarget" style="position: absolute; left: -999em; top: -999em;"></iframe>
public void UploadImage(HttpPostedFileBase imageFile)
{
if (imageFile != null)
{
byte[] logo = new byte[imageFile.ContentLength];
imageFile.InputStream.Read(logo, 0, imageFile.ContentLength);
...
}
}
【解决方案2】:
我做了一个教程,你可以在我的博客上看到它:
http://developmentpassion.blogspot.com/2013/08/aspnet-mvc-ajax-file-uploading-using.html
代码如下:
@using (Html.BeginForm("Upload","TestDetails", FormMethod.Post,
new
{
enctype = "multipart/form-data",
id = "ImgForm",
name = "ImgForm",
target = "UploadTarget"
}))
{
<input type="hidden" id="bookingdid" name="bookingdid" value="@Model.BookingDId" />
<a class="close-reveal-modal"><img alt="close" src="@Url.Content("~/images/crossicon.png")" width="32" /></a>
<div style="width:100px; margin:auto;float:left;line-height:30px;font-weight:bold;">File</div>
<div style="width:200px;float:left;margin:auto;">
<input type="file" id="uploadFile" name="file" data-val="true" data-val-required="please select a file" />
<span id="validityMessages" style="color:Red;"></span>
</div>
<div style="clear:both;"></div>
<div style="width:auto; margin-top:3%;">
<div style="margin:5% 18%;">
<input id="upload" type="submit" value="Upload" name="Upload" onclick="UploadImage()" />
<span id="uploadLoader" style="display:none;"><img id="searchLoader" src="../Images/loader.gif" />Uploading Please Wait</span>
</div>
</div>
}
<div id="uploadsContainer"></div>
<iframe id="UploadTarget" name="UploadTarget" onload="UploadImage_Complete();" style="position: absolute; left: -999em; top: -999em;"></iframe>
</div>
我的上传类:
public class Uploads
{
public string FilePath { get; set; }
public long bookingdid { get; set; }
public string FileName { get; set; }
}
这里是动作:
[HttpPost]
public ActionResult Upload(FormCollection form,HttpPostedFileBase file)
{
//HttpPostedFileBase file = Request.Files[0 ];
Uploads uploadsModel = new Uploads();
uploadsModel.bookingdid = long.Parse(form["bookingdid"]);
uploadsModel.FileName = file.FileName;
uploadsModel.FilePath = "~/Uploads/" + file.FileName;
if (file.ContentLength < 1048576)
{
if (file != null)
{
file.SaveAs(Server.MapPath(uploadsModel.FilePath));
}
TestDetailsViewModel objTestDetails = new TestDetailsViewModel();
objTestDetails.SaveFile(uploadsModel);
}
return PartialView("~/Views/Shared/_UploadsPartial.cshtml",uploadsModel);
}
希望对你有帮助