使用文件上载控件过滤文件类型

sub*_*ash 11 c# asp.net file-upload

如何使用asp.net&c#.net中的文件上传控件过滤文件类型

例如,单击文件上传控件的浏览按钮时,应该只打开excel文件类型的浏览文件对话框.

这怎么可能

小智 9

这是其他论坛的答案

我认为如果你使用C#(或VB,net)和.net fileupload控件很容易实现它.您可以在arraylist"allowedExtensions"中定义文件类型.

string upload_Image(FileUpload fileupload, string ImageSavedPath)
{
    FileUpload fu = fileupload;  
    string imagepath = "";
    if (fileupload.HasFile)
    {
        string filepath = Server.MapPath(ImageSavedPath);  
        String fileExtension = System.IO.Path.GetExtension(fu.FileName).ToLower();
        String[] allowedExtensions = { ".gif", ".png", ".jpeg", ".jpg" };
        for (int i = 0; i < allowedExtensions.Length; i++)
        {
            if (fileExtension == allowedExtensions[i])
            {
                try
                {
                    string s_newfilename = DateTime.Now.Year.ToString() +
                        DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() +
                        DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() +                           DateTime.Now.Second.ToString() +  fileExtension; 
                        fu.PostedFile.SaveAs(filepath + s_newfilename);

                   imagepath = ImageSavedPath + s_newfilename;
               }
               catch (Exception ex)
               {
                   Response.Write("File could not be uploaded.");
               }

           }

       }

   }
   return imagepath;
}
Run Code Online (Sandbox Code Playgroud)

  • @LojiSmith你认为包含函数到底是什么?它遍历迭代.上面的代码没有任何问题,除非他们找到匹配后没有突破循环... (2认同)

小智 9

它完美无缺!

<asp:FileUpload ID="FileUpload1" runat="server" accept=".xls, .xlsx"/>
Run Code Online (Sandbox Code Playgroud)