zoukankan      html  css  js  c++  java
  • 取得文件真正扩展名类型

    实现这个功能,需要使用一个System.IO名称空间。只需判断文件流前两个字节即可。

    参考代码:

    View Code
     string GetFileCass(string path)
        {
            
    try
            {
                FileStream fs 
    = new FileStream(path, FileMode.Open, FileAccess.Read);
                BinaryReader reader 
    = new BinaryReader(fs);
                
    string fileClass = string.Empty;
                
    byte buffer;

                
    byte[] b = new byte[2];
                buffer 
    = reader.ReadByte();
                b[
    0= buffer;
                fileClass 
    = buffer.ToString();
                buffer 
    = reader.ReadByte();
                b[
    1= buffer;
                fileClass 
    += buffer.ToString();
                reader.Close();
                fs.Close();

                
    return fileClass;
            }
            
    catch
            {
                
    return string.Empty;
            }
        }

    例子演示:

    <asp:FileUpload ID="FileUpload1" runat="server" /><br />    
        
    <asp:Button ID="Button1" runat="server" Text="Get File Extension Info" onclick="Button1_Click" /><br />
        
    <p></p>
        
    <asp:Label ID="lblExtension" runat="server" Text=""></asp:Label><br />
        
    <asp:Label ID="lblFileClass" runat="server" Text=""></asp:Label>

    按钮事件:

    View Code
     protected void Button1_Click(object sender, EventArgs e)
        {
            
    if (!File.Exists(this.FileUpload1.PostedFile.FileName))
            {
                
    //follow Js class, download address:http://www.cnblogs.com/insus/articles/1341703.html
                Insus.NET.InsusJsUtility objJs = new Insus.NET.InsusJsUtility();
                objJs.JsAlert(
    "You did not specify a file.");
                
    return;
            }

            
    string path = this.FileUpload1.PostedFile.FileName;
            
    this.lblExtension.Text ="Extension: "+ path.Substring(path.LastIndexOf("."));
            
    this.lblFileClass.Text = "FileClass: " +  GetFileCass(path);
        }

    选择一个Excel文件得到的结果:

  • 相关阅读:
    Caused by: Unable to load bean: type: class:com.opensymphony.xwork2.ObjectFactory
    nable to load bean: type:com.opensymphony.xwork2.util.ValueStackFactory
    一个web项目web.xml的配置中<context-param>配置作用
    js获取form的方法
    HTML <legend> 标签
    Struts2 文件上传 之 文件类型 allowedTypes
    Struts2验证框架的配置及validation.xml常用的验证规则
    struts2学习笔记--使用Validator校验数据
    LeetCode204:Count Primes
    《采访中收集程序猿》学习记录5
  • 原文地址:https://www.cnblogs.com/insus/p/1980495.html
Copyright © 2011-2022 走看看