Core mvc:文件不会保存在wwwroot文件夹中,而是使用"wwwroot.....JPG"根目录中的名称



图像上传在Windows环境中的开发服务器中运行良好,但是当我在远程Linux服务器中运行代码时,文件被上传,但在根文件夹中,并且网站无法访问其文件。

public async Task<IActionResult> Index(IList<IFormFile> files,Type type)
{
Startup.Progress = 0;

foreach (IFormFile source in files)
{
if (isFileImage(source))
{
string filename = ContentDispositionHeaderValue.Parse(source.ContentDisposition).FileName.ToString().Trim('"');
filename = this.EnsureCorrectFilename(filename);
string serverFilePath = this.GetPathAndFilename(filename);
try
{
await source.CopyToAsync(new FileStream(serverFilePath,FileMode.Create));
}
catch (Exception e)
{
}
finally
{
}
}
}
return Content("Success");
}
private string GetPathAndFilename(string filename)
{
string path = Path.Combine(Directory.GetCurrentDirectory(),@"wwwrootimagesmaterials", filename);
return path;
}

这是负责上传图像的代码。在开发窗口环境中,当文件保存在"wwwroot\images\materials"文件夹中时,它可以完美地工作。 但是当代码运行时,远程Linux服务文件会上传,但保存在根文件夹中,名称为"wwwroot\images\materials*.jpg"。即使在远程服务器中的开发模式下运行代码时,也会出现此问题。

由于您使用的是Path.Combine因此我建议将路径的每个部分作为参数传递。因此,您不会将它们作为一个参数@"wwwrootimagesmaterials",而是将它们分别传递"wwwroot", "images", "materials"

试试这个简单。在这种情况下,您必须注入_hostingEnvironment才能获得ContentRootPath

string folderName = "Upload/Profile/" + user.Id;
string webRootPath = _hostingEnvironment.ContentRootPath;
string newPath = Path.Combine(webRootPath, folderName);
if (!Directory.Exists(newPath))
{
Directory.CreateDirectory(newPath);
}
string extention = file.ContentType.Split("/")[1];
string fileName = user.Id + ".jpg";
string fullPath = Path.Combine(newPath, fileName);
string envpath = folderName + "/" + fileName;
using (var stream = new FileStream(fullPath, FileMode.Create))
{
file.CopyTo(stream);
}

最新更新