在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(),@"wwwroot\images\materials", filename);
return path;
}
这是负责上传图像的代码。在开发Windows环境中,当文件保存在“ wwwroot \ images \ materials”文件夹中时,它可以完美工作。 但是,运行代码时,Remote Linux会提供已上传的文件,但会以“ wwwroot \ images \ materials * .jpg”名称保存在根文件夹中。即使在远程服务器上以开发模式运行代码时,也会发生此问题。
答案 0 :(得分:1)
由于您使用的是Path.Combine
,因此建议您将路径的每个部分作为参数传递。因此,您不必将@"wwwroot\images\materials"
作为一个参数,而是分别将它们传递给"wwwroot", "images", "materials"
。
答案 1 :(得分:0)
尝试简单。为此,您必须注入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);
}
OnCreate