C# · 12月 27, 2021

c# – 使用文件上传控件过滤文件类型

如何使用文件上传控件在asp.net& C#.NET

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

这怎么可能

解决方法 这是另一个论坛的答案

如果您使用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;}