[英]Core mvc: Files not getting saved in wwwroot folder but creating files with "wwwroot.....jpg" name in the root
The image uploading is working perfectly in the development server in the windows environment but when I run the code in the Remote Linux server, the files get uploaded but in the root folder and for which the files can not be accessed by the website.图像上传在 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;
}
This is the code responsible for uploading an image.这是负责上传图片的代码。 In the development windows environment, it works perfectly as the files get saved in the "wwwroot\\images\\materials" folder.在开发 Windows 环境中,它完美地工作,因为文件保存在“wwwroot\\images\\materials”文件夹中。 But when the code is run the Remote Linux serves the files get uploaded but are saved in the root folder with "wwwroot\\images\\materials*.jpg" name.但是当代码运行时,远程 Linux 服务会上传文件,但会以“wwwroot\\images\\materials*.jpg”名称保存在根文件夹中。 Even when running the code in development mode in the Remote server this problem occurs.即使在远程服务器中以开发模式运行代码时也会出现此问题。
Since you're using Path.Combine
I would suggest passing each part of the path as a parameter.由于您使用的是Path.Combine
我建议将路径的每个部分作为参数传递。 So instead of @"wwwroot\\images\\materials"
as one parameter, you would pass them separately "wwwroot", "images", "materials"
.因此,不要将@"wwwroot\\images\\materials"
作为一个参数,而是将它们分别传递给"wwwroot", "images", "materials"
。
Try this simple.试试这个简单的。 In this you have to inject _hostingEnvironment
so you can get ContentRootPath
在此您必须注入_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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.