简体   繁体   English

在使用“文件上传”浏览以选择要上传的文件时,如何限制其他格式的文件不显示?

[英]How to restrict the other format files from Displaying while browsing with File Upload for Selecting a File to Upload?

In my Project I am Uploading Doc or PDF file for the Reference of the User during the "File Upload" browse all the files including Doc and PDF files are displaying to select so I used IF condition in my Code to check whther the file selected was DOC or PDF but I want only DOC and PDF files to be displayed for selection to discard the IF statement my Code is, 在我的项目中,我正在“文档上传”期间上传Doc或PDF文件供用户参考,浏览包括Doc和PDF文件在内的所有文件,以供选择,因此我在代码中使用了IF条件来检查所选文件是否为DOC或PDF,但我只希望显示DOC和PDF文件供选择,以放弃我的代码为IF语句,

        if (FileUpload1.HasFile != false)
        {
            // Read the file and convert it to Byte Array

            string filePath = FileUpload1.PostedFile.FileName;

            int size = FileUpload1.PostedFile.ContentLength;

            string filename = Path.GetFileName(filePath);

            string ext = Path.GetExtension(filename);

            string contenttype = String.Empty;

            int bufferSize = 1;
            byte[] buffer = new byte[bufferSize];

            //Set the contenttype based on File Extension

            switch (ext)
            {

                case ".doc":

                    contenttype = "application/vnd.ms-word";

                    break;
                case ".docx":

                    contenttype = "application/vnd.ms-word";

                    break;

                case ".pdf":

                    contenttype = "application/pdf";

                    break;

            }
            if (size <= 5242880)
            {
                if (contenttype != String.Empty && ext == ".doc" || ext == ".docx" || ext == ".pdf")
                {

                    Stream fs = FileUpload1.PostedFile.InputStream;

                    BinaryReader br = new BinaryReader(fs);

                    Byte[] bytes = br.ReadBytes((Int32)fs.Length);
                    string fname = @"E:\Rajesh_Kumar\Application\Valuation\ExamManagement\ExamManagement\FileUpload";
                    Directory.CreateDirectory(fname);
                    string strFullFilename = @"E:\Rajesh_Kumar\Application\Valuation\ExamManagement\ExamManagement\FileUpload\" + FileUpload1.FileName;
                    //SqlCommand   qry = new SqlCommand("select Filepath from answerkey");
                     FileInfo file = new FileInfo(strFullFilename);
                    //FileInfo file1 = new FileInfo(qry);
                    fname = Path.Combine(fname, strFullFilename);
                    if(file.Exists)
                    {
                        lblMessage.Visible = true;
                        lblMessage.ForeColor = System.Drawing.Color.Red;

                        lblMessage.Text = "File - ''"+filename+"'' - already Exists in the Database !!!";
                        FileUpload1.Focus();
                   }
                    else
                    {


                        //insert the file into database
                        string strQuery = "insert into answerkey(Filename, Type, Data,Filepath)" + " values (@Filename, @Type, @Data,@Filepath)";

                        SqlCommand cmd = new SqlCommand(strQuery);

                        cmd.Parameters.Add("@Filename", SqlDbType.VarChar).Value = filename;

                        cmd.Parameters.Add("@Type", SqlDbType.VarChar).Value = contenttype;

                        cmd.Parameters.Add("@Data", SqlDbType.Binary).Value = bytes;

                        cmd.Parameters.Add("@Filepath", SqlDbType.VarChar).Value = filePath;

                        InsertUpdateData(cmd);
                        File.Copy(filePath, strFullFilename, true);
                       lblMessage.Visible = true;

                        lblMessage.ForeColor = System.Drawing.Color.Green;

                        string filename1 = Path.GetFileNameWithoutExtension(filename);

                        lblMessage.Text =  "File -      '' " + filename1 + " ''  - of Size - ''" + size + " bytes''  - has been Uploaded Successfully";


                    }
                }
                else
                {
                    lblMessage.Visible = true;
                    lblMessage.ForeColor = System.Drawing.Color.Red;

                    lblMessage.Text = "File format not recognised.Upload Word/PDF formats Only";
                    FileUpload1.Focus();


                }


            }
            else
            {
                lblMessage.Visible = true;
                lblMessage.ForeColor = System.Drawing.Color.Red;

                lblMessage.Text = "File Size is larger than 5 MB !!!";
                FileUpload1.Focus();
            }

        }
        else
        {
            lblMessage.Visible = true;
            lblMessage.ForeColor = System.Drawing.Color.Red;

            lblMessage.Text = "Please Select a File !!!";
            FileUpload1.Focus();

        }


        }

Thanks in Advance... 提前致谢...

In case of web, you cannot do that. 如果是网络,则无法执行此操作。

For a way around, you can see the link: 有关解决方法,您可以查看链接:
How to restrict file type in FileUpload control 如何在FileUpload控件中限制文件类型

Use Regular Expression Validator: 使用正则表达式验证器:

<asp:RegularExpressionValidator
                id="RegularExpressionValidator1" runat="server"
                ErrorMessage="Only Word and PDF files are allowed!"
                ValidationExpression="^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))(.pdf|.PDF|.doc|.DOC|.docx|.DOCX)$"
                ControlToValidate="FileUpload1" CssClass="text-red"></asp:RegularExpressionValidator>

Hope this will help :) 希望这会有所帮助:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM