Hans
Hans

Reputation: 2852

File upload: How to check if any file is selected using Multipart file-upload

I'm developing a web api to upload file using Multipart file-upload following the instructions here: https://www.asp.net/web-api/overview/advanced/sending-html-form-data-part-2 . I wounder if there is any way to check if any file is selected or not. Yes the length can be checked if it is zero but what if an empty file was actually uploaded.

Upvotes: 0

Views: 1768

Answers (2)

Hans
Hans

Reputation: 2852

I found Headers.ContentDisposition.FileName useful to check. Because a file should have a name.

Upvotes: 0

Julius Depulla
Julius Depulla

Reputation: 1633

Yes you can. You have already mentioned the length property, you can also check the expected file extension, e.g., .jpeg, jpg, .png, .gif, .swf, .pdf, .doc, .docx etc.

When the user uploads the file, get the file path

public string GetFileExtension(){
   string fileName = Server.MapPath(FileUpload1.FileName);
   string extension = Path.GetExtension(fileName);
   return extension;
}

//Validate

    public bool IsValidFileExtension(string fileExtension)
    {
       switch(fileExtension)
       {
         case ".jpeg":
            return true; 
            break;

           case ".jpeg":
            return true; 
            break;
          default:
            return false;
       }

      return false;
   }

//Validate

string fileExtension = GetFileExtension(fileExtension);
bool IsValidFile = IsValidFileExtension(fileExtension);

Upvotes: 1

Related Questions