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;
}