簡體   English   中英

核心 mvc:文件未保存在 wwwroot 文件夾中,而是在根目錄中創建名稱為“wwwroot .....jpg”的文件

[英]Core mvc: Files not getting saved in wwwroot folder but creating files with "wwwroot.....jpg" name in the root

圖像上傳在 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”文件夾中。 但是當代碼運行時,遠程 Linux 服務會上傳文件,但會以“wwwroot\\images\\materials*.jpg”名稱保存在根文件夾中。 即使在遠程服務器中以開發模式運行代碼時也會出現此問題。

由於您使用的是Path.Combine我建議將路徑的每個部分作為參數傳遞。 因此,不要將@"wwwroot\\images\\materials"作為一個參數,而是將它們分別傳遞給"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);
            }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM