(FYI, I would make sure that the code you have has been verified to work before you change anything.)
If you're trying to limit what file types can be uploaded, you should be able to check both the file type (Content Type) or the extension.
The ContentType should be something like "image/png" or "image/jpeg". You can find lists of the images types online, I found this answer which had a lot of the common ones: https://stackoverflow.com/a/14587821/13734398
To check the extension I believe you could parse the filename like this using Path.GetExtension:
var extension = Path.GetExtension(file.FileName);
(Path is from the System.IO namespace. Either use System.IO.Path...
or add using System.IO;
to the top of your C# file)
Then you can check the extension for ".png" or ".jpeg" for example.
Client-side Checks
Oh, and your question mentioned "before upload". Technically, at this point the file has already been uploaded. If you're trying to limit what gets uploaded at all, you could add some client side checks to the upload form. Note that it isn't bulletproof, and you still need to check server side like I mentioned above.
Other Advice
Personally, I would recommend refactoring your code a tiny bit as well. Here is what I would make it look like:
public IActionResult UploadFile ([FromForm] IFormFile file, [FromForm] string fileName)
{
var fileId = _fileService.UploadFile(fileName, file);
return Ok (new {
id = fileId,
fileName = file.FileName,
fileSize = file.Length,
fileType = file.ContentType,
// Removing this from the Response.
// Probably don't need to send the file back.
// file = file
});
}
I think this will give you better error messages if something goes wrong with UploadFile()
. It's also (to me) a bit more clear about the sequence/order of things.