Esempio n. 1
0
        public async Task <JsonResult> AddBanner(AddBannerDto dto, IFormFile uploadFile)
        {
            if (uploadFile == null)
            {
                return(Json(new ResponseDto {
                    Code = 0, Message = "请上传图片!"
                }));
            }

            var webRootPath     = _hostEnvironment.ContentRootPath;
            var relativeDirPath = "wwwroot\\UploadFiles\\BannerPic";
            var absolutePath    = Path.Combine(webRootPath, relativeDirPath);

            var fileTypes = new string[] { ".gif", ".jpg", ".jpeg", ".png", ".bmp" };
            var extension = Path.GetExtension(uploadFile.FileName);

            if (!fileTypes.Contains(extension.ToLower()))
            {
                return(Json(new ResponseDto {
                    Code = 0, Message = "图片格式有误!"
                }));
            }

            if (!Directory.Exists(absolutePath))
            {
                Directory.CreateDirectory(absolutePath);
            }

            var fileName = DateTime.Now.ToString("yyyyMMddHHmmss") + extension;
            var filePath = Path.Combine(absolutePath, fileName);

            await using (var stream = new FileStream(filePath, FileMode.Create))
            {
                await uploadFile.CopyToAsync(stream);
            }
            dto.Image = Path.Combine("/UploadFiles/BannerPic/", fileName);
            return(Json(_bannerAppService.AddBanner(dto)));
        }