C# Core mvc:文件不会保存在wwwroot文件夹中,而是使用“创建文件”;wwwroot…..jpg“;根目录中的名称
图像上传在windows环境下的开发服务器上工作得很好,但是当我在远程Linux服务器上运行代码时,文件被上传到根文件夹中,并且网站无法访问这些文件C# Core mvc:文件不会保存在wwwroot文件夹中,而是使用“创建文件”;wwwroot…..jpg“;根目录中的名称,c#,asp.net-mvc,asp.net-core,C#,Asp.net Mvc,Asp.net Core,图像上传在windows环境下的开发服务器上工作得很好,但是当我在远程Linux服务器上运行代码时,文件被上传到根文件夹中,并且网站无法访问这些文件 public async Task<IActionResult> Index(IList<IFormFile> files,Type type) { Startup.Progress = 0; foreach (IFormFile source in files)
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(),@"wwwroot\images\materials", filename);
return path;
}
公共异步任务索引(IList文件,类型)
{
启动进度=0;
foreach(文件中的文件源)
{
if(isFileImage(源))
{
字符串filename=ContentDispositionHeaderValue.Parse(source.ContentDisposition.filename.ToString().Trim(“”);
filename=this.EnsureCorrectFilename(文件名);
string serverFilePath=this.GetPathAndFilename(文件名);
尝试
{
等待source.CopyToAsync(新文件流(serverFilePath,FileMode.Create));
}
捕获(例外e)
{
}
最后
{
}
}
}
返回内容(“成功”);
}
私有字符串GetPathAndFilename(字符串文件名)
{
字符串路径=path.Combine(Directory.GetCurrentDirectory(),@“wwwroot\images\materials”,文件名);
返回路径;
}
这是负责上载图像的代码。在开发windows环境中,当文件保存在“wwwroot\images\materials”文件夹中时,它可以完美地工作。
但是,当代码运行时,远程Linux服务将上载文件,但这些文件保存在根文件夹中,名为“wwwroot\images\materials*.jpg”“名字。即使在远程服务器上以开发模式运行代码,也会出现此问题。因为您使用的是
Path.Combine
我建议将路径的每个部分作为参数传递。因此,您不需要将“wwwroot\images\materials”作为一个参数来传递,而是将它们分别传递给“wwwroot”、“images”、“materials”
。在这种情况下,您必须注入\u 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);
}
非常感谢:D。这正是我想要的。在此之前,我在发布之前使用的是forwardshash而不是反斜杠。。