.Net Core

.Net Core 6.0 异步上传文件报错 404

2022-12-10  本文已影响0人  Rinaloving

1. 说明


        [HttpPost]
        public async Task<MessageModel<string>> UploadFileAsync(IFormFile file)
        {
            var fileName = Path.GetRandomFileName() + Path.GetExtension(file.FileName);

            //拼接完整的文件存储路径
            var filePath = Path.Combine(_environment.ContentRootPath, fileName);

            using (var fs = System.IO.File.Create(filePath))
            {
                await file.CopyToAsync(fs);
            }
            return new MessageModel<string>()
            {
                success = true,
                msg = "创建成功",
                response = fileName
            };
        }

2. 解决

[HttpPost]
        public async Task<MessageModel<string>> UploadFile([FromServices] IHostEnvironment env, UserInfo input)
        {
            try
            {
                string filename = string.Empty;
                filename = Path.Combine("file", Guid.NewGuid().ToString() + input.HeadPortrait);
                using (var stream = new FileStream(Path.Combine(env.ContentRootPath,filename),FileMode.CreateNew))
                {

                }
                var entity = _mapper.Map<UserInfo>(input);
                entity.CreateTime = DateTime.Now;
                await _userInfoService.InsertAsync(entity, true);
                return new MessageModel<string>()
                {
                    success = true,
                    msg = "创建成功",
                    response = filename
                };
            }
            catch (Exception ex)
            {
                return new MessageModel<string>()
                {
                    success = false,
                    msg = "异常",
                    response = null
                };
            }

        }
上一篇下一篇

猜你喜欢

热点阅读