The official file upload documentation covers this information.
Image Upload in Blazor WASM
![](https://techprofile.blob.core.windows.net/images/TOhomo8VV0GN94bZZ-vmYA.png?8D9301)
hey,
I done image uploading using blazor wasm and asp.net core hosted. The thing I also want is to change the filename before saving into folder and also check the file is less than 5mb before saving.
here is my code -
2 answers
Sort by: Most helpful
-
-
Zhi Lv - MSFT 32,106 Reputation points Microsoft Vendor
2021-12-09T06:23:18.363+00:00 Hi @Prathamesh Shende ,
I done image uploading using blazor wasm and asp.net core hosted. The thing I also want is to change the filename before saving into folder and also check the file is less than 5mb before saving.
Do you mean you have achieved the upload function, and now you want to change the file name and check the file length? If that is the case, you could try to modify your code as below (see the inline comments):
[HttpPost] public IActionResult Upload() { try { var file = Request.Form.Files[0]; var folderName = Path.Combine("StaticFiles", "Images"); var pathToSave = Path.Combine(Directory.GetCurrentDirectory(), folderName); // save the file if less than 5 MB if (file.Length > 0 && file.Length < 5242880) { // you are building the file name at here, var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"'); // generate the new file path, var fullPath = Path.Combine(pathToSave, fileName); var dbPath = Path.Combine(folderName, fileName); // then, it will create a new file (with the new file name) based on the fullPath. using (var stream = new FileStream(fullPath, FileMode.Create)) { file.CopyTo(stream); } return Ok(dbPath); } else { return BadRequest(); } }
You can also refer to my sample code:
//check the file length if (fileviewmodel.File.Length > 0 && fileviewmodel.File.Length < 5242880) { //in this sample, the new file will stored in the `wwwroot\files` folder, and the new file name is start with the current date var filePath = Path.Combine(_hostingEnvironment.WebRootPath, "files", DateTime.Now.ToString("dd_mm_yyyy") + fileviewmodel.File.FileName); using (var stream = System.IO.File.Create(filePath)) { await fileviewmodel.File.CopyToAsync(stream); } }
The result is like this:
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.Best regards,
Dillion