引言
在.NET MVC框架中,文件上传下载是常见的功能需求。高效地处理文件上传下载不仅能提升用户体验,还能减轻服务器负担。本文将详细介绍在.NET MVC中如何实现高效文件上传下载。
文件上传
1. 使用ASP.NET MVC内置的FileUpload控件
ASP.NET MVC内置的FileUpload控件可以方便地实现文件上传。以下是一个简单的示例:
@model FileUploadModel
<h2>文件上传</h2>
<form action="/Upload" method="post" enctype="multipart/form-data">
<input type="file" name="file" />
<input type="submit" value="上传" />
</form>
public class FileUploadController : Controller
{
[HttpPost]
public ActionResult Upload(HttpPostedFileBase file)
{
if (file != null && file.ContentLength > 0)
{
var path = Path.Combine(Server.MapPath("~/UploadedFiles"), file.FileName);
file.SaveAs(path);
}
return RedirectToAction("Index");
}
}
2. 使用第三方库
除了ASP.NET MVC内置的FileUpload控件,还可以使用第三方库如jQuery File Upload实现更丰富的功能。以下是一个简单的示例:
<link rel="stylesheet" href="https://blueimp.github.io/jquery-file-upload/css/jquery.fileupload.css">
<script src="https://blueimp.github.io/jquery-file-upload/js/vendor/jquery.ui.widget.js"></script>
<script src="https://blueimp.github.io/jquery-file-upload/js/jquery.iframe-transport.js"></script>
<script src="https://blueimp.github.io/jquery-file-upload/js/jquery.fileupload.js"></script>
<form id="fileupload" action="/Upload" method="post" enctype="multipart/form-data">
<input type="file" name="files[]" multiple>
<button type="submit" class="btn btn-primary">上传</button>
</form>
<noscript>
<style>.modal { display: block; position: fixed; }</style>
<div class="modal fade" id="myModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">提示</h4>
</div>
<div class="modal-body">
<p>您的浏览器不支持HTML5文件上传,请升级您的浏览器。</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
</div>
</div>
</div>
</div>
</noscript>
public class FileUploadController : Controller
{
[HttpPost]
public ActionResult Upload()
{
if (Request.Files.Count > 0)
{
foreach (string file in Request.Files)
{
var postedFile = Request.Files[file];
var path = Path.Combine(Server.MapPath("~/UploadedFiles"), postedFile.FileName);
postedFile.SaveAs(path);
}
}
return RedirectToAction("Index");
}
}
文件下载
1. 使用File方法
在.NET MVC中,可以使用File方法实现文件下载。以下是一个简单的示例:
public ActionResult Download(string fileName)
{
var path = Path.Combine(Server.MapPath("~/UploadedFiles"), fileName);
return File(path, "application/octet-stream", fileName);
}
2. 使用FileStream
如果文件较大,可以使用FileStream实现文件下载。以下是一个简单的示例:
public ActionResult Download(string fileName)
{
var path = Path.Combine(Server.MapPath("~/UploadedFiles"), fileName);
byte[] buffer = new byte[1024];
int bytesRead;
using (var stream = new FileStream(path, FileMode.Open, FileAccess.Read))
{
return File(stream, "application/octet-stream", fileName);
}
}
总结
本文介绍了.NET MVC中高效文件上传下载的技巧。通过使用ASP.NET MVC内置的FileUpload控件、第三方库以及File和FileStream方法,可以方便地实现文件上传下载功能。在实际开发中,根据需求选择合适的方法,可以提升用户体验和系统性能。
