.Net6使用HttpClient上传图片时老是提示404NotFound
王递杰 2023年10月31日 .Net
使用.Net6做了两个MVC项目,需要其中一个向另外一个通过Http接口上传图片,在本地上传没有问题,但是发布到服务器IIS上面之后,始终报404错误。
上传端代码:
public static async Task<string> PostMainImg(IFormFile file)
{
using Stream fileStream = file.OpenReadStream();
byte[] fileBytes = StreamToBytes(fileStream);
ByteArrayContent fileContent = new ByteArrayContent(fileBytes);
fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
{
Name = "file",
FileName = file.FileName
};
MultipartFormDataContent content = new MultipartFormDataContent();
content.Add(fileContent);
using HttpClient httpClient = new HttpClient();
var response = await httpClient.PostAsync(_mainImgUrl, content);
if (response.IsSuccessStatusCode)
{
var str = await response.Content.ReadAsStringAsync();
return str;
}
return null;
}
服务端代码:
[HttpPost("ImgUpload")]
public async Task<IActionResult> ImgUpload()
{
var files = Request.Form.Files;
if (files.Count <= 0)
return new JsonResult(new { code = 0, msg = "请选择上传文件" });
string date = DateTime.Now.ToString("yyyyMMdd");
string uploadPath = Path.Combine(_webHostEnvironment.WebRootPath, "images");
if (!Directory.Exists(uploadPath))
Directory.CreateDirectory(uploadPath);
List<string> imgUrl = new List<string>();
foreach (var file in files)
{
//文件后缀
var fileExtension = Path.GetExtension(file.FileName).ToLower();
//判断后缀是否是图片
string[] fileFilt = { ".gif", ".jpeg", ".jpg", ".png" };
if (!fileFilt.Contains(fileExtension))
return new JsonResult(new { code = 0, msg = "请上传jpg、png、gif格式的图片" });
//判断文件大小
long length = file.Length;
if (length > 1024 * 1024 * 20) //2M
return new JsonResult(new { code = 0, msg = "上传的文件不能大于20M" });
//文件名
string fileName = $"{Path.GetRandomFileName()}{fileExtension}";
string filePath = Path.Combine(uploadPath, fileName);
using (var stream = new FileStream(filePath, FileMode.Create))
{
await file.CopyToAsync(stream);
}
imgUrl.Add($"/images/{fileName}");
}
if (imgUrl.Count > 0)
return new JsonResult(new { code = 1, msg = "", data = imgUrl });
else
return new JsonResult(new { code = 0, msg = "上传失败" });
}
本来以为是项目的问题,后来我又新建了一个单独的空项目,把代码复制过去重新发布来进行测试。没想到这次竟然报以下错误:
System.UnauthorizedAccessException: Access to the path 'C:\Windows\TEMP\ASPNETCORE_e65c14f7-e337-493c-90ac-d49a48db7187.tmp' is denied.
上面那个报404的问题我在网上没有找到解决方式,但是这个报错网上有解决方案,那就是在网站对应 的应用程序池将 高级设置中 “加载用户文件配置” 设置为True。
我试了以后,问题果然解决了。
上面报404错误那个问题用此方法也完美解决!
相关博客
评论
暂无评论
随笔分类
Powered by .NET 6.0 陕ICP备2020018176号-4