![](/img/trans.png)
[英]How to use IFormFile as property when uploading file to a server using Asp.NET Core 3.1 framework?
[英]How to change file name when uploading using IFormFile
我有以下代碼(我仍在開發它)成功上傳文件到所需的路徑。
private async Task AddImage(IFormFile image, string filePath)
{
List<string> PermittedFileTypes = new List<string> {
"image/jpeg",
"image/png",
};
if (PermittedFileTypes.Contains(image.ContentType)) {
// HERE I WILL CHECK NAME AND CHANGE IF IT ALREADY EXSISTS
using (var stream = new FileStream(Path.Combine(filePath, image.FileName), FileMode.Create))
{
await image.CopyToAsync(stream);
}
}
}
我正在嘗試使用相同的名稱(顯然是獲取錯誤)上傳文件,但文件不同。 所以我想檢查文件是否存在,如果它確實更改了文件的名稱,可能會在末尾附加一個“_#”,然后在新名稱下再次上傳文件。問題是IFormFile.FileName只是for get,我無法設置文件名。
在線查看我看到人們建議將文件復制到新名稱,但由於文件無法上傳,我無法做到。 任何幫助表示贊賞!
您可以使用Path.Combine(filePath, Guid.NewGuid() )
而不是Path.Combine(filePath, image.FileName)
來保證文件名是唯一的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.