开发者

How to restrict the files to image type using file upload in asp.net

开发者 https://www.devze.com 2023-01-06 15:27 出处:网络
i am using file upload, i wanted to restrict the files showing in the dialog box to images only. That is \'Files of Type\' in the dialog box should be .jpg,.j开发者_JAVA百科peg,.gif,.bmp,.pngYou can\'

i am using file upload, i wanted to restrict the files showing in the dialog box to images only. That is 'Files of Type' in the dialog box should be .jpg,.j开发者_JAVA百科peg,.gif,.bmp,.png


You can't. Web browsers don't allow you to do things like filter the list by filetype or set the default directory for the file upload dialog.

As Darin and Chris have suggested, once the user has selected a file you can use javascript to parse the filename and alert the user if it doesn't look like the file is of the right type. Depending on what you are going to do with the file you should consider do something on the server side to verify that the file is valid image and not something bad .

Alternatively, you could look into using Silverlight's OpenFileDialog or maybe even a Flash control. See http://www.plupload.com, http://www.uploadify.com/, http://swfupload.org/ etc...


You could use a regular expression validator.


You'll want to do this two ways: one on the client for ease of use, and then once on the server to protect against users disabling the client side validation. Both approaches are described here.


I know this is very old but With Fileuploads in asp. If I want to lock to content to be a certain type like image or video I just do a contains on the content type.

if (FileUpload1.HasFile) {

    if (FileUpload1.PostedFile.ContentType.Contains("image/")) {
//rest of your logic
    }

}


this function is used to check whether the file that user want to upload is valid file type or not.

private bool IsValidFile(string filePath)
    {
        bool isValid = false;

        string[] fileExtensions = { ".BMP", ".JPG", ".PNG", ".GIF", ".JPEG" };

        for (int i = 0; i < fileExtensions.Length; i++)
        {
            if (filePath.ToUpper().Contains(fileExtensions[i]))
            {
                isValid = true; break;
            }
        }
        return isValid;
    }

This function used to check file type & file size. If file is invalid than it will return error message.

private string ValidateImage(HttpPostedFile myFile)
   {
       string msg = null;
       int FileMaxSize = Convert.ToInt32(ConfigurationManager.AppSettings["FileUploadSizeLimit"].ToString());
       //Check Length of File is Valid or Not.
       if (myFile.ContentLength > FileMaxSize)
       {
           msg = msg + "File Size is Too Large.";
       }
       //Check File Type is Valid or Not.
       if (!IsValidFile(myFile.FileName))
       {
           msg = msg + "Invalid File Type.";
       }
       return msg;
   }
0

精彩评论

暂无评论...
验证码 换一张
取 消