博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[实战]MVC5+EF6+MySql企业网盘实战(18)——文件上传,下载,修改
阅读量:5778 次
发布时间:2019-06-18

本文共 19447 字,大约阅读时间需要 64 分钟。

写在前面

经过一段时间的秀秀改改,终于把文件上传下载,修改文件夹文件名称的功能实现了。

系列文章

[实战]MVC5+EF6+MySql企业网盘实战(18)——文件上传,下载,修改

实现逻辑

按照上篇文章的思路,对代码进行了修改,发现这种方式更简单一点。每次修改文件夹的名称,不需要再去考虑修改文件夹名称导致文件路径的问题,直接修改文件夹名称即可。

public class HomeController : Controller    {        private IUserInfoServiceRepository _userInfoServiceRepository = new UserInfoServiceRepository();        private IMyFileServiceRepository _myFileServiceRepository = new MyFileServiceRepository();        private ILogServiceRepository _logServiceRepository = new LogServiceRepository();        [HttpGet]        public ActionResult FileList(int? id)        {            UserInfo userInfo = Session["user"] as UserInfo;            if (userInfo == null)            {                return RedirectToAction("Login", "UserInfo");            }            Expression
> where = null; //不存在则创建 var user = _userInfoServiceRepository.Find(x => x.Id == userInfo.Id); var rootFolder = _myFileServiceRepository.Find(x => x.User.Id == userInfo.Id && x.IsFolder == true && x.ParentId == 0); if (rootFolder == null) { rootFolder = _myFileServiceRepository.Add(new MyFile() { IsDelete = false, Name = "NetDisk", ParentId = 0, IsFolder = true, FileExt = string.Empty, FileIcon = "/Content/Images/FolderType.png", ModifyDt = DateTime.Now, FileMd5 = string.Empty, FileSize = 0, CreateDt = DateTime.Now, User = user }); _myFileServiceRepository.SaveChanges(); } if (id == null || id == 0) { where = x => x.User.Id == userInfo.Id && x.ParentId == rootFolder.Id && x.IsDelete == false; } else { where = x => x.User.Id == userInfo.Id && x.ParentId == id && x.IsDelete == false; } var fileList = _myFileServiceRepository.FindAll(where).OrderByDescending(x => x.IsFolder); ViewBag.UserInfo = userInfo; ViewBag.ChildTitle = "我的网盘"; ViewBag.Id = id; _logServiceRepository.Add(new Log() { Message = "网盘首页", Level = LogLevel.INFO, UserName = userInfo.UserName, Opt = "网盘首页" }); _logServiceRepository.SaveChanges(); return View(fileList); } [HttpPost] public void UploadFile(int? id) { UserInfo userInfo = Session["user"] as UserInfo; //保证路径格式一直以/结束 if (userInfo == null) { RedirectToAction("Login", "UserInfo"); } int iParentId = Convert.ToInt32(id); Expression
> findWhere = null; if (id == null || id == 0) { findWhere = x => x.ParentId == iParentId && x.User.Id == userInfo.Id && x.IsFolder == true; } else { findWhere = x => x.Id == iParentId && x.User.Id == userInfo.Id && x.IsFolder == true; } var fatherFolder = _myFileServiceRepository.Find(findWhere); var files = Request.Files; MyFile myFile = null; if (files.Count > 0) { var file = files[0]; string fileName = file.FileName; Stream inputStream = file.InputStream; string fileSaveFolder = Server.MapPath("~/NetDisk"); //如果目标不存在,则创建 if (!Directory.Exists(fileSaveFolder)) { Directory.CreateDirectory(fileSaveFolder); } byte[] buffer = new byte[inputStream.Length]; //判断是否已经超出个人网盘大小 var myFiles = _myFileServiceRepository.FindAll(x => x.User.Id == userInfo.Id && x.IsDelete == false); int myDiskSize = 0; if (myFiles.Count() > 0) { myDiskSize = myFiles.Sum(x => x.FileSize); } //如果已经超出网盘大小,则给出提示 if (myDiskSize + buffer.Length > userInfo.NetDiskSize) { AlertMsg("对不起,您的网盘空间不足,请清理后再次上传,或联系管理员进行扩容。", ""); return; } inputStream.Read(buffer, 0, buffer.Length); string strFileMd5 = MD5Helper.GetMD5FromFile(buffer); //名称格式一律以md5命名。 string strNewName = strFileMd5 + Path.GetExtension(file.FileName); string fileSavePath = Path.Combine(fileSaveFolder, strNewName); //如果文件不存在,则保存物理文件。 if (!System.IO.File.Exists(fileSavePath)) { file.SaveAs(fileSavePath); } //判断在数据库中同一路径下,md5相同的文件是否存在,不存在则直接插入,否则判断在当前用户的网盘中该文件的个数,进行自动重命名保存。 var fileIsExistList = _myFileServiceRepository.FindAll(x => x.FileMd5 == strFileMd5 && x.ParentId == fatherFolder.Id); //如果找到的文件对象不为空,并且是删除状态,则修改删除状态,不再新增文件信息,否则添加。 //查询导航属性 var currentUser = _userInfoServiceRepository.Find(x => x.Id == userInfo.Id); if (fileIsExistList.Count() > 0) { myFile = fileIsExistList.FirstOrDefault(); //文件被逻辑删除了,则更新状态,将该文件的信息赋值给当前的用户,否则重命名后新增文件。 myFile.IsDelete = false; myFile.User = currentUser; myFile.ParentId = fatherFolder == null ? iParentId : fatherFolder.Id; if (myFile.IsDelete) { _myFileServiceRepository.Update(myFile); } else { //查找该用户下类似文件名的文件并且没有被逻辑删除的个数 fileName = fileName.Substring(0, fileName.LastIndexOf('.')); iParentId = fatherFolder == null ? iParentId : fatherFolder.Id; var count = fileIsExistList.Where(x => x.User.Id == userInfo.Id && x.IsDelete == false && x.Name.Contains(fileName) && x.ParentId == iParentId).Count(); fileName = count > 0 ? Path.GetFileNameWithoutExtension(fileName) + "(" + (count + 1).ToString() + ")" + Path.GetExtension(fileName) : fileName; myFile.Name = fileName; //保存数据库 _myFileServiceRepository.Add(myFile); } } else { //新增文件信息 myFile = new MyFile() { FileMd5 = strFileMd5, ModifyDt = DateTime.Now, IsDelete = false, FileSize = buffer.Length, ParentId = fatherFolder == null ? iParentId : fatherFolder.Id, FileExt = Path.GetExtension(fileSavePath), CreateDt = DateTime.Now, Name = fileName, FileIcon = GetFileIcon(Path.GetExtension(fileSavePath)), User = currentUser, IsFolder = false }; //保存数据库 _myFileServiceRepository.Add(myFile); } _logServiceRepository.Add(new Log() { Message = "上传" + myFile.Name, Level = LogLevel.INFO, UserName = userInfo.UserName, Opt = "上传" + myFile.Name }); _logServiceRepository.SaveChanges(); _myFileServiceRepository.SaveChanges(); string json = new JavaScriptSerializer().Serialize(myFile); AlertMsg("上传成功", json); } } private void AlertMsg(string msg, string fileJson) { Response.ContentType = "text/html"; Response.Write("
"); Response.End(); } private string GetFileIcon(string fileExt) { string fileIconPath = "/Content/Images/"; switch (fileExt.ToLower()) { case ".doc": case ".docx": fileIconPath += "DocType.png"; break; case ".xlx": case ".xlxs": fileIconPath += "XlsType.png"; break; case ".ppt": case ".pptx": fileIconPath += "PptType.png"; break; case ".pdf": fileIconPath += "PdfType.png"; break; case ".apk": fileIconPath += "ApkType.png"; break; case ".dwt": case ".dwg": case ".dws": case ".dxf": fileIconPath += "CADType.png"; break; case ".exe": fileIconPath += "ExeType.png"; break; case ".png": case ".gif": case ".jpg": fileIconPath += "ImgType.png"; break; case ".txt": fileIconPath += "TxtType.png"; break; case ".bt": fileIconPath += "TorrentType.png"; break; case ".rmvb": case ".avi": case ".flv": fileIconPath += "VideoType.png"; break; case ".zip": case ".7z": case ".rar": fileIconPath += "RarType.png"; break; case ".mp3": fileIconPath += "MusicType.png"; break; default: fileIconPath += "OtherType.png"; break; } return fileIconPath; } ///
/// 文件下载 /// ///
public void DownLoadFile(string fileId) { UserInfo userInfo = Session["user"] as UserInfo; if (userInfo == null) { RedirectToAction("Login", "UserInfo"); return; } if (string.IsNullOrEmpty(fileId)) { throw new ArgumentNullException("fileId is errror"); } int id = Convert.ToInt32(fileId); var findFile = _myFileServiceRepository.Find(x => x.Id == id); if (findFile == null) { AlertMsg("文件不存在", ""); return; } _logServiceRepository.Add(new Log() { Message = "下载" + findFile.Name, Level = LogLevel.INFO, UserName = userInfo.UserName, Opt = "下载" + findFile.Name }); _logServiceRepository.SaveChanges(); string filePath = Path.Combine(Server.MapPath("~/NetDisk/"), findFile.FileMd5 + findFile.FileExt); //以字符流的形式下载文件 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(findFile.Name, System.Text.Encoding.UTF8)); Response.BinaryWrite(bytes); Response.Flush(); Response.End(); } public void DeleteFile(string fileId) { UserInfo userInfo = Session["user"] as UserInfo; if (userInfo == null) { RedirectToAction("Login", "UserInfo"); return; } if (string.IsNullOrEmpty(fileId)) { throw new ArgumentNullException("fileId is errror"); } int id = Convert.ToInt32(fileId); var findFile = _myFileServiceRepository.Find(x => x.Id == id); if (findFile == null) { AlertMsg("文件不存在", ""); return; } _logServiceRepository.Add(new Log() { Message = "删除" + findFile.Name, Level = LogLevel.INFO, UserName = userInfo.UserName, Opt = "删除" + findFile.Name }); _logServiceRepository.SaveChanges(); findFile.IsDelete = true; _myFileServiceRepository.Update(findFile); int count = _myFileServiceRepository.SaveChanges(); if (count > 0) { var response = new { code = 4, fileId = findFile.Id }; Response.Write(new JavaScriptSerializer().Serialize(response)); } } public JsonResult EditFileName() { string fileId = Request.Form["fileId"]; string fileNewName = Request.Form["fileNewName"]; UserInfo userInfo = Session["user"] as UserInfo; if (userInfo == null) { RedirectToAction("Login", "UserInfo"); } int id = Convert.ToInt32(fileId); var findFile = _myFileServiceRepository.Find(x => x.Id == id); findFile.Name = fileNewName; _myFileServiceRepository.Update(findFile); int count = _myFileServiceRepository.SaveChanges(); if (count > 0) { var response = new { code = 200, msg = "更新成功" }; return new JsonResult() { Data = new JavaScriptSerializer().Serialize(response) }; } _logServiceRepository.Add(new Log() { Message = "修改" + findFile.Name, Level = LogLevel.INFO, UserName = userInfo.UserName, Opt = "修改" + findFile.Name }); _logServiceRepository.SaveChanges(); return new JsonResult() { Data = new JavaScriptSerializer().Serialize(new { code = 500, msg = "保存失败" }) }; } public JsonResult CreateFolder(int? id) { UserInfo userInfo = Session["user"] as UserInfo; if (userInfo == null) { RedirectToAction("Login", "UserInfo"); } int parentId = Convert.ToInt32(id); string folderName = Request.Params["folderName"]; if (string.IsNullOrEmpty(folderName)) { throw new ArgumentNullException("文件夹名称不能为空"); } var fatherFolder = _myFileServiceRepository.Find(x => x.User.Id == userInfo.Id && x.IsFolder == true && x.ParentId == parentId); parentId = fatherFolder == null ? parentId : fatherFolder.Id; var count = _myFileServiceRepository.FindAll(x => x.IsFolder == true && x.IsDelete == false && x.User.Id == userInfo.Id && x.Name.Contains(folderName) && x.ParentId == parentId).Count(); userInfo = _userInfoServiceRepository.Find(x => x.Id == userInfo.Id); if (count > 0) { //如果不存在,则新建,否则进行自动重命名 folderName = folderName + "(" + (count + 1).ToString() + ")"; } MyFile folder = new MyFile() { Name = folderName, CreateDt = DateTime.Now, User = userInfo, FileExt = string.Empty, FileIcon = "/Content/Images/FolderType.png", FileMd5 = string.Empty, FileSize = 0, IsDelete = false, ModifyDt = DateTime.Now, IsFolder = true, ParentId = fatherFolder == null ? parentId : fatherFolder.Id }; try { _myFileServiceRepository.Add(folder); _myFileServiceRepository.SaveChanges(); _logServiceRepository.Add(new Log() { Message = "创建文件夹" + folder.Name, Level = LogLevel.INFO, UserName = userInfo.UserName, Opt = "创建文件夹" + folder.Name }); _logServiceRepository.SaveChanges(); } catch (Exception) { return new JsonResult() { Data = new JavaScriptSerializer().Serialize(new { code = 500, msg = "创建失败" }) }; } return new JsonResult() { Data = new JavaScriptSerializer().Serialize(new { code = 200, folder = folder }) }; } public JsonResult EditFolder() { UserInfo userInfo = Session["user"] as UserInfo; if (userInfo == null) { RedirectToAction("Login", "UserInfo"); } string strId = Request.Params["fileId"]; string strNewFolderName = Request.Params["fileNewName"]; JavaScriptSerializer jss = new JavaScriptSerializer(); if (string.IsNullOrEmpty(strId)) { return new JsonResult() { Data = jss.Serialize(new { code = 500, msg = "请选择要编辑的文件夹" }) }; } if (string.IsNullOrEmpty(strNewFolderName)) { return new JsonResult() { Data = jss.Serialize(new { code = 500, msg = "文件夹名称不能为空" }) }; } int folderId = Convert.ToInt32(strId); var findFolder = _myFileServiceRepository.Find(x => x.Id == folderId && x.User.Id == userInfo.Id && x.IsDelete == false); if (findFolder != null) { string strOldFolderName = findFolder.Name + "/"; //找到所有的目录,以 findFolder.FileName 结尾的目录,并修改 var folders = new List
();//_myFileServiceRepository.FindAll(x => x.User.Id == userInfo.Id && x.FolderPath.EndsWith(strOldFolderName) && x.IsDelete == false); foreach (var item in folders) { _myFileServiceRepository.Update(item); } findFolder.Name = strNewFolderName; _myFileServiceRepository.Update(findFolder); _myFileServiceRepository.SaveChanges(); _logServiceRepository.Add(new Log() { Message = "修改文件夹" + findFolder.Name, Level = LogLevel.INFO, UserName = userInfo.UserName, Opt = "修改文件夹" + findFolder.Name }); _logServiceRepository.SaveChanges(); } return new JsonResult() { Data = jss.Serialize(new { code = 200, msg = "修改成功" }) }; } }
HomeController

View

@model IEnumerable
@{ ViewBag.Title = "FileList"; Layout = "~/Views/Shared/_Layout.cshtml";}
@{
int i = 0;} @foreach (var item in Model) { i++;
@{ if (!@item.IsFolder) {
} else {
} }
}
文件名 大小 修改日期 操作
@item.Name @item.FileSize 字节 @item.Name @item.Name @item.ModifyDt 编辑 删除 @{ if (@item.FileMd5 != "") { 下载 } }
FileList.cshtml

总结

网盘的样子已经有了,下一步实现文件列表的分页实现。

转载地址:http://sakyx.baihongyu.com/

你可能感兴趣的文章
邮件发送1
查看>>
[转] libcurl异步方式使用总结(附流程图)
查看>>
编译安装LNMP
查看>>
[转]基于display:table的CSS布局
查看>>
crm 02--->讲师页面及逻辑
查看>>
AS3.0 Bitmap类实现图片3D旋转效果
查看>>
Eigen ,MKL和 matlab 矩阵乘法速度比较
查看>>
带三角的面包屑导航栏(新增递增数字)
查看>>
Web应用程序安全与风险
查看>>
codeforces 984 A. Game
查看>>
CSS居中
查看>>
One Person Game(概率+数学)
查看>>
CodeForces 258B Little Elephant and Elections :于1-m中找出七个数,使六个数里面的4和7个数比第七个数严格小:数位dp+dfs...
查看>>
MAP
查看>>
手把手教你测——上网快鸟
查看>>
用javascript获取地址栏参数
查看>>
一起谈.NET技术,你应该知道的15个Silverlight诀窍
查看>>
商教助手!解析夏普液晶高清宽屏投影机系列
查看>>
云南去年有望实现151万贫困人口净脱贫
查看>>
Java架构师面试题系列整理(大全)
查看>>