MVC中的文件上传-小结
普通Controller实现文件上传
<h2>Upload</h2> @using (Html.BeginForm("Upload", "Home", FormMethod.Post, new { enctype = "multipart/form-data" })) { <div> <h4>Select a file:</h4> <input name="files" id="files" type="file" /> <label id="lbError">@ViewBag.ErrorMessage</label> <input type="submit" name="submit" value="Upload" /> </div> }
[HttpPost] public ActionResult Upload(IEnumerable<HttpPostedFileBase> files) { if (files == null || files.Count() == 0 || files.ToList()[0] == null) { ViewBag.ErrorMessage = "Please select a file!!"; return View(); } string filePath = string.Empty; Guid gid = Guid.NewGuid(); foreach (HttpPostedFileBase file in files) { filePath = Path.Combine(HttpContext.Server.MapPath("/Uploads/"), gid.ToString() + Path.GetExtension(file.FileName)); file.SaveAs(filePath); } return RedirectToAction("UploadResult", new { filePath = filePath }); } public ActionResult UploadResult(string filePath) { ViewBag.FilePath = filePath; return View(); }
<system.web> <httpRuntime maxRequestLength="153600" executionTimeout="900" /> </system.web>
<system.webServer> <security> <requestFiltering> <requestLimits maxAllowedContentLength="157286400" /> </requestFiltering> </security> </system.webServer>
ApiController实现文件上传
通过ApiController来实现文件上传时,不得不参考一下 官方文档了,建议先去阅读一下。
<h2>API Upload</h2> <form name="apiForm" method="post" enctype="multipart/form-data" action="/api/upload"> <div> <label for="apifiles">Select a File</label> <input name="apifiles" type="file" /> </div> <div> <input type="submit" value="Upload" /> </div> </form>
public class UploadController : ApiController { public Task<HttpResponseMessage> PostFormData() { if (!Request.Content.IsMimeMultipartContent()) { throw new Exception(""); } string root = HttpContext.Current.Server.MapPath("/Uploads/"); var provider = new ReNameMultipartFormDataStreamProvider(root); var task = Request.Content.ReadAsMultipartAsync(provider).ContinueWith<HttpResponseMessage>(t => { if (t.IsFaulted || t.IsCanceled) { Request.CreateErrorResponse(HttpStatusCode.InternalServerError, t.Exception); } string fileName = string.Empty; foreach (MultipartFileData file in provider.FileData) { fileName = file.LocalFileName; } //返回上传后的文件全路径 return new HttpResponseMessage() { Content = new StringContent(fileName) }; }); return task; } } /// <summary> /// 重命名上传的文件 /// </summary> public class ReNameMultipartFormDataStreamProvider : MultipartFormDataStreamProvider { public ReNameMultipartFormDataStreamProvider(string root) : base(root) { } public override string GetLocalFileName(System.Net.Http.Headers.HttpContentHeaders headers) { //截取文件扩展名 string exp = Path.GetExtension(headers.ContentDisposition.FileName.TrimStart(‘\"‘).TrimEnd(‘\"‘)); string name = base.GetLocalFileName(headers); return name + exp; } }
如上代码,区别与官网给出的.net 4.0 版本的代码的。
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。