上传文件类的写法
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using System.Data.SqlClient;

/// <summary>
/// UpFile 的摘要说明
/// </summary>
public class UpFile:Page
{
    private string upfilepath;
    private string upfilesize;
    private string upfiletype;
    private string strconnectionstring ;
 public UpFile()
 {
        //upfilepath          = Page.Server.MapPath(System.Configuration.ConfigurationManager.AppSettings["UpFilePath"].ToString());
        upfilesize          = System.Configuration.ConfigurationManager.AppSettings["UpFileSize"].ToString();
        upfiletype          = System.Configuration.ConfigurationManager.AppSettings["UpFileType"].ToString();
        strconnectionstring = System.Configuration.ConfigurationManager.AppSettings["DBConnetion"];
 }
    /// <summary>
    /// 保存文件
    /// </summary>
    /// <param name="file"></param>
    /// <returns>1 成功 0 失败 2 大小超过限制 3 文件格式不对 4 文件已经存在</returns>
    public int SaveAs(HttpPostedFile file, string task_id, string stage_id, string add_userid,string attach_desc,  string edit_time)
    {
        string filename = file.FileName.ToString().Split('\\')[file.FileName.ToString().Split('\\').Length - 1];
        string filederectory = upfilepath + "\\" + DateTime.Now.ToString("yyyyMM");
        string filenamestring = filederectory+"\\"+ filename;

        int sizeflag = 0;
        int size = file.ContentLength;
        if (size / 1024 < int.Parse(upfilesize))
        {
            sizeflag = 1;
        }
        else
        {
            return 2;
        }

        int typeflag = 0;
        string extraname = filename.Split('.')[1];
        string[] extranamearray = upfiletype.Split('|');
        for (int i = 0; i < extranamearray.Length; i++)
        {
            if (extranamearray[i].ToString() == extraname)
                typeflag = 1;
        }
        if (typeflag == 0)
        {
            return 3;
        }

        ///******************
        ///如果是数据库存放文件路径的话
        ///******************

        //if (System.IO.File.Exists(filenamestring))
        //{
        //    return 4;
 
        //}
        //try
        //{
        //    if (!System.IO.File.Exists(filederectory))
        //        System.IO.Directory.CreateDirectory(filederectory);
        //    file.SaveAs(filenamestring);
        //}
        //catch( Exception ex)
        //{
        //    string aa = ex.Message;
        //    return 0;
        //}

        ///******************
        ///如果是数据库存放文件二进制数据的话
        ///******************
        System.IO.Stream streamdata;
        streamdata = file.InputStream;
        int bytesize = file.ContentLength;
        byte[] databyte = new byte[bytesize];
        int status = streamdata.Read(databyte, 0, bytesize);


        string strsql = "insert into ubt_task_attach (attach_filename,task_id,stage_id,add_userid,attach_desc,edit_time,ATTACH_CONTEXT) ";
        strsql += "values (";
        strsql += "@attach_filename,@task_id,@stage_id,@add_userid,@attach_desc,@edit_time,@ATTACH_CONTEXT)";

        SqlParameter[] commandparameters =
                                            {
                                                new SqlParameter("@attach_filename", filename),
                                                new SqlParameter("@task_id", task_id),
                                                new SqlParameter("@stage_id", stage_id),
                                                new SqlParameter("@add_userid", add_userid),
                                                new SqlParameter("@attach_desc", attach_desc),
                                                new SqlParameter("@edit_time",edit_time),
                                                new SqlParameter("@ATTACH_CONTEXT",databyte)
                                            };
        SqlHelper.ExecuteNonQuery(strconnectionstring, CommandType.Text, strsql, commandparameters);
        return 1;
    }
    /// <summary>
    /// 查看某一任务下的所有附件
    /// </summary>
    /// <param name="connection"></param>
    /// <param name="taskid"></param>
    /// <returns></returns>
    public static DataSet GetAttachList(string connection, string taskid,string stageid,string userid)
    {
        string strsql = "select  * from ubt_task_attach where task_id = @task_id and stage_id= @stageid and add_userid =@userid ";
        return SqlHelper.ExecuteDataset(connection, CommandType.Text, strsql, new SqlParameter("@task_id", taskid), new SqlParameter("@stageid", stageid), new SqlParameter("@userid", userid));
    }

    //public void GetAttachDetail(string upfilepath,string upfilename,)
    //{

    //}
    /// <summary>
    /// 删除
    /// </summary>
    /// <param name="connection"></param>
    /// <param name="attachid"></param>
    /// <param name="username"></param>
    /// <returns>1 成功 2 没有权限 3 失败</returns>
    public int DeleteAttach(string connection,string attachid,string username)
    {


        //组织成较完整的事务.....
        try
        {
            //删除文件
            string strsql_getdetail = "select * from ubt_task_attach where attach_id = " + attachid;
            SqlDataReader dr = SqlHelper.ExecuteReader(connection, CommandType.Text, strsql_getdetail);
            string name ="";
            string username_db = "";
            while(dr.Read())
            {
                name =  Convert.ToDateTime(dr["edit_time"].ToString()).ToString("yyyyMM") +"\\"+ dr["attach_filename"].ToString();
                username_db = dr["add_userid"].ToString();
            }
            if(username!=username_db)
            {
                return 2;
            }
           
            name = upfilepath+"\\"+name;
            if(System.IO.File.Exists(name))
            System.IO.File.Delete(name);
            //删除数据库
            string strsql = "delete from ubt_task_attach where attach_id = " + attachid;
            SqlHelper.ExecuteNonQuery(connection, CommandType.Text, strsql);

            return 1;
        }
        catch
        {
            return 0;

        }
    }

    public static SqlDataReader GetAttachContext(string connection,string fileid,string user)
    {
        string strsql = "select attach_context,attach_filename from  UBT_TASK_ATTACH where ATTACH_ID = " + fileid + " and user = '" + user + "'" ;
        return SqlHelper.ExecuteReader(connection, CommandType.Text, strsql);
 
    }
}
读数据库二进制文件的写法
           if (!Page.IsPostBack)
        {
            if (Request.QueryString["attachid"] != null)
            {
                if (Request.QueryString["attachid"] != "")
                {
                    string connection = System.Configuration.ConfigurationManager.AppSettings["DBConnetion"].ToString();

                    string user = Page.User.Identity.Name.ToString();
                    SqlDataReader dr = UpFile.GetAttachContext(connection, Request.QueryString["attachid"].ToString(), user);
                    byte[] buffer = new byte[0];
                    string attachname = "";
                    string attachtype = "";
                    while (dr.Read())
                    {
                        buffer = (byte[])dr["attach_context"];
                        attachname = dr["attach_filename"];
                    }
                    dr.Close();
                    if (attachname != "")
                    {
                        attachtype = attachname.Split(',')[1].ToString();
                    }
                    else
                    {
                        Response.Write("<script language='javascript'>alert('您没有权限查看此文件');</script>");
                        return;
                    }

                    Response.Clear();
                    Response.AddHeader("content-length", buffer.Length.ToString());
                    Response.AddHeader("Content-disposition", "inline;filename=" + attachname + ";");  //可以设置打开或者下载文件时用户看到的文件名称

                    string[] upfiletypearray = System.Configuration.ConfigurationManager.AppSettings["UpFileType"].ToString().Split('|');
                    string[] upfiletypeapplicationarray = System.Configuration.ConfigurationManager.AppSettings["UpFileTypeApplication"].ToString().Split('|');
                    int arrayindex = 0;
                    for (int i = 0; i < upfiletypearray.Length; i++)
                    {
                        if (upfiletypearray[i].ToString() == attachtype)
                        {
                            arrayindex = i;
                            break;
                        }
                    }
                    string upfiletypeapplication = upfiletypeapplicationarray[arrayindex].ToString();
                    if (upfiletypeapplication!="other")
                    Response.ContentType = "application/" + upfiletypeapplication;  //web页面解析二进制的格式 对应文件的mime类型
                    
                    try
                    {
                        Response.BinaryWrite(buffer);
                    }
                    catch
                    {

                    }
                    Response.End();


                }
            }

        }
webconfig中设置
  <add key="UpFileType" value="doc|xls|rar|jpg|gif|bmp|jpeg|png"/>
  <!--上传文件类型-->
  <add key="UpFileTypeApplication" value="msword|vnd.ms-excel|x-rar-compressed|other|other|other|other|other"/>
  <!--上传文件解析类型       须和上传文件类型一一对应-->

具体mime类型可以在网上搜索

posted on 2007-08-10 10:58  恶整冒黑烟  阅读(228)  评论(0)    收藏  举报