上传
<form action="/Home/UploadFile" method="post" enctype="multipart/form-data"> <input type="file" name="file" /><br /> <input type="submit" value="提交" /> </form>
后台
[HttpPost] public ActionResult UploadFile(HttpPostedFileBase file) { string basePath = System.AppDomain.CurrentDomain.BaseDirectory; var files = Request.Files; //获得文件的方法 if (files != null && files.Count >1) { #region 执行多个文件上传 for (int i = 0; i < files.Count; i++) { HttpPostedFileBase fileitem = files[i]; //判定文件的大小 string strExtension = Path.GetExtension(fileitem.FileName); double dFileSize = fileitem.ContentLength; if (dFileSize > 5242880)//1024*1024*5) { return Content("<script>alert('" + fileitem.FileName + "文件大于5MB')</script>"); } else { //创建文件 string filePath = "~/Files"; Directory.CreateDirectory(Server.MapPath(filePath)); //创建唯一的文件名 string fileName = Guid.NewGuid().ToString(); string fFullDir = filePath + fileName + strExtension; fileitem.SaveAs(Server.MapPath(fFullDir)); } } #endregion } else { #region 执行单个文件上传 if (file != null) { //可以判断它的大小格式 //创建文件夹 string filePath = "~/Files"; string path = Server.MapPath(filePath); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } int size = file.ContentLength; string timePath = DateTime.Now.ToString("yyyyMMddHHmmss"); string fileName = timePath+file.FileName; string pathh = Path.Combine(path, fileName); file.SaveAs(pathh); //return Content("<script>alert('上传成功!');location.href=" // + Url.Content(filePath) + "</script>"); } #endregion } return View(); }
下载:
<li>@Html.ActionLink("文件下载", "FileDown", "Home")</li>
public FileStreamResult FileDown() {
//把Files文件夹下的“常用方法.txt”记事本保存到电脑上,保存后的记事本名字为“aaa.txt” string fileName = "aaa.txt";//客户端保存的文件名 string filePath = Server.MapPath("~/Files/常用方法.txt");//路径 "D:\abc.xls";//文件路径 return File(new FileStream(filePath, FileMode.Open), "text/plain", fileName); }
网上的方法:
方式一: public FileStreamResult DownFile(string filePath, string fileName) { string absoluFilePath = Server.MapPath(System.Configuration.ConfigurationManager.AppSettings["AttachmentPath"] + filePath); return File(new FileStream(absoluFilePath, FileMode.Open), "application/octet-stream", Server.UrlEncode(fileName)); } 方式二: public ActionResult DownFile(string filePath, string fileName) { filePath = Server.MapPath(System.Configuration.ConfigurationManager.AppSettings["AttachmentPath"] + filePath);
//以字符流的形式下载文件
FileStream fs = new FileStream(filePath, FileMode.Open);
byte[] bytes = new byte[(int)fs.Length];
fs.Read(bytes, 0, bytes.Length);
fs.Close();
Response.ContentType = "application/octet-stream";
//通知浏览器下载文件而不是打开
Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
return new EmptyResult();
}
View调用: <a href="/Document/DownFile?filePath=@item.Value&fileName=@item.Key">下载</a>