C#文件上传与下载实现
C#的文件上传下载功能,说实话,真挺常用的,尤其是在做后台管理或者 Web 工具类项目的时候。用 ASP.NET 的HttpPostedFileBase
上传,写法也不复杂,响应也快,代码看着还挺清爽的。
上传这块,用个带input type="file"
的表单收文件,后台直接在 Action 里接收HttpPostedFileBase
。文件不为空就SaveAs
搞定,顺便用Json
给前端个反馈,体验也挺友好。
像这样:
[HttpPost]
public ActionResult Upload(HttpPostedFileBase file)
{
if (file != null && file.ContentLength > 0)
{
string fileName = Path.GetFileName(file.FileName);
string uploadPath = Server.MapPath("~/uploads/");
file.SaveAs(Path.Combine(uploadPath, fileName));
return Json(new { success = true, message = "文件上传成功!" });
}
else
{
return Json(new { success = false, message = "选择文件后再上传!" });
}
}
下载这部分嘛,也不麻烦。用FileResult
返回文件流,浏览器会自动弹下载框。想让用户下哪个文件,就把路径拼好给它。
比如:
public FileResult Download(string filePath)
{
string downloadPath = Server.MapPath(filePath);
return File(downloadPath, "application/octet-stream", Path.GetFileName(filePath));
}
哦对了,如果你要做大文件,建议搞个断点续传或分块上传,避免一下子把服务器撑爆。还有像文件类型、大小校验这些,最好提前下,省得用户上传个奇奇怪怪的东西。
如果你刚好在做 Web 文件管理模块,可以参考下这几个相关的案例,ASP.NET MVC AJAX 文件上传示例这个就还蛮实用的。
253.72KB
文件大小:
评论区