美文网首页.Net Core
.Net Core 6.0 异步上传文件报错 404

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

作者: Rinaloving | 来源:发表于2022-12-10 17:12 被阅读0次

    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. 解决

    • 我也是百度到一位大神遇到的同样情况,如果是异步上传(net core 3.0 之后),方法名后不要带有 Async (有点神奇)
    • 修改代码
    [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
                    };
                }
    
            }
    

    相关文章

      网友评论

        本文标题:.Net Core 6.0 异步上传文件报错 404

        本文链接:https://www.haomeiwen.com/subject/mbkxqdtx.html