コード例 #1
0
        public bool upload(string name, long userId, long noteId, bool isAttach, out long serverFileId, out string msg)
        {
            if (isAttach)
            {
                return(uploadAttach(name, userId, noteId, out msg, out serverFileId));
            }
            msg          = "";
            serverFileId = 0;

            var uploadDirPath = $"{RuntimeEnvironment.DirectorySeparatorChar}www/upload/{userId.ToString("x")}/images/{DateTime.Now.ToString("yyyy_MM")}/";

            if (RuntimeEnvironment.IsWindows)
            {
                uploadDirPath = $@"upload\{userId.ToString("x")}\images\{DateTime.Now.ToString("yyyy_MM")}\";
            }
            var diskFileId = SnowFlake_Net.GenerateSnowFlakeID();

            serverFileId = diskFileId;
            var httpFiles = _accessor.HttpContext.Request.Form.Files;

            //检查是否登录
            if (userId == 0)
            {
                userId = GetUserIdBySession();
                if (userId == 0)
                {
                    msg = "NoLogin";
                    return(false);
                }
            }

            if (httpFiles == null || httpFiles.Count < 1)
            {
                return(false);
            }
            var httpFile = httpFiles[name];
            var fileEXT  = Path.GetExtension(httpFile.FileName).Replace(".", "");

            if (!IsAllowImageExt(fileEXT))
            {
                msg = $"The_image_extension_{fileEXT}_is_blocked";
                return(false);
            }
            var fileName = diskFileId.ToString("x") + "." + fileEXT;

            //判断合法性
            if (httpFiles == null || httpFile.Length < 0)
            {
                return(false);
            }
            //将文件保存在磁盘
            Task <bool> task   = SaveUploadFileOnDiskAsync(httpFile, uploadDirPath, fileName);
            bool        result = task.Result;

            if (result)
            {
                //将结果保存在数据库
                NoteFile noteFile = new NoteFile()
                {
                    FileId      = diskFileId,
                    UserId      = userId,
                    AlbumId     = 1,
                    Name        = fileName,
                    Title       = fileName,
                    Path        = uploadDirPath + fileName,
                    Size        = httpFile.Length,
                    CreatedTime = DateTime.Now
                                  //todo: 增加特性=图片管理
                };
                var AddResult = FileService.AddImage(noteFile, 0, userId, true);
                if (!AddResult)
                {
                    msg = "添加数据库失败";
                }
                return(AddResult);
            }
            else
            {
                msg = "磁盘保存失败";
                return(false);
            }
        }