2017-04-08 75 views
0

嗨,我想在上傳到服務器之前更改文件名並在數據庫中存儲路徑 。這是我的代碼。但它上傳具有相同名稱的文件。我想 想改名(帶guid)。我怎樣才能做到這一點?在上傳到服務器之前更改文件名asp.net核心

[HttpPost, ValidateAntiForgeryToken] 
     public async Task<IActionResult> SaveAsync(NewPostViewModel model, IFormFile postImage) 
     { 

      var unitOfWork = new UnitOfWork(new NewsDbContext(_contextOptions)); 

      // My domain class which is contains CoverPhotoPath property 
      var post = new Post(); 

      if (postImage != null && postImage.Length > 0) 
      { 
       string filename = ContentDispositionHeaderValue.Parse(postImage.ContentDisposition).FileName.Trim('"'); 

       filename = this.EnsureCorrectFilename(filename); 
       using (FileStream output = System.IO.File.Create(this.GetPathAndFilename(filename))) 
        await postImage.CopyToAsync(output); 
      // this is my photo path in database 
       post.CoverPhotoPath = filename; 
      } 


      unitOfWork.Posts.Add(post); 
      unitOfWork.Compelete(); 

      return RedirectToAction("List", "News"); 
     } 

我的方法

private string EnsureCorrectFilename(string filename) 
     { 
      if (filename.Contains("\\")) 
       filename = filename.Substring(filename.LastIndexOf("\\") + 1); 

      return filename; 
     } 


private string GetPathAndFilename(string filename) 
    { 
     return _environment.WebRootPath + "\\files\\" + filename; 
    } 

回答

0

這是使用的FileStream我的上傳方法,希望它有助於

[HttpPost] 
    public async Task<IActionResult> UploadFileImage(ICollection<IFormFile> files) 
    { 
     string file_name = "the file name"; 
     var uploads = Path.Combine(_environment.WebRootPath, "uploads/Image"); 
     foreach (var file in files) 
     { 
      if (file.Length > 0) 
      { 
       using (var fileStream = new FileStream(Path.Combine(uploads, file_name), FileMode.Create)) 
       { 
        await file.CopyToAsync(fileStream); 
       } 
      } 
     } 
     return View(); 
    } 
相關問題