参考
http://www.cnblogs.com/likailinux/archive/2008/06/28/1231537.html
http://www.cnblogs.com/chinahawk681/articles/56436.html
http://www.cnblogs.com/wfyfngu/archive/2008/10/09/1307390.html

解决方案 »

  1.   

    上传文件   
    参数说明
    FileBox:表单名称
    BasePath:文件基路径
    FileSize:文件大小
    LastError:错误信息
    Extension:文件扩展名
    FilePath:文件保存路径
    FileName:文件保存名称
    Name:文件原名称
    public static bool UploadMyFiles(System.Web.UI.HtmlControls.HtmlInputFile FileBox,string BasalPath,String SavePath,ref decimal FileSize,out string LastError,out String Extension ,out String FilePath,out String FileName,out string Name)
    {
    DateTime datTime=System.DateTime.Now;
    String strTemp;
    string strFileName = FileBox.PostedFile.FileName;
    bool blnResult;
    LastError="";
    Name="";
    FilePath="";
    FileName="";
    Extension="";try
    {
    if (strFileName=="")
    {
    LastError="请点击浏览选择要上传的文件!";
    return false;
    }
    if(Convert.ToDecimal(FileBox.PostedFile.ContentLength)<=FileSize*1048576)
    {
    FileSize = FileBox.PostedFile.ContentLength/1024;
    CStat xStat = new CStat();
    xStat.UserID = System.Web.HttpContext.Current.Session["CurrentUserID"].ToString();
    if(xStat.Load())
    {
    bool sessionVIP;
    if(System.Web.HttpContext.Current.Session["BankVIP"] == null)
    {
    sessionVIP = false;
    }
    else
    {
    sessionVIP = true;
    }
    if(xStat.FilesSize+FileSize>=Function.FeeOrFreeFile(sessionVIP))
    {
    System.Web.HttpContext.Current.Response.Redirect("~/blog/NotEnoughFile.htm");
    }
    }
    Name=Path.GetFileName(strFileName);
    Extension=Path.GetExtension(strFileName);
    Extension=Extension.ToLower();
    // if(true)//文件符合要求
    // {
    strTemp = datTime.ToShortDateString().Replace( "-", "");
    FileName = strTemp + datTime.ToLongTimeString().Replace(":","")+datTime.Millisecond+ Extension;
    FilePath = SavePath + strTemp + "/";CreateDirectory(BasalPath + FilePath);FileBox.PostedFile.SaveAs(BasalPath + FilePath + FileName);
    blnResult=true;
    }
    else
    {
    blnResult=false;
    LastError="上传的文件大小应在"+(FileSize).ToString()+"M以内!";
    }
    }
    catch (Exception ex)
    {
    throw new System.Exception((ex.Message 
    + ("\r\n" + ex.StackTrace)));
    }
    return blnResult;

     
      

  2.   

    保存在数据库里、数据库备份比较好、
    default.aspx  
    <%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml" >
    <head runat="server">
        <title>无标题页</title>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
          <asp:FileUpload ID="FileUpload1" runat="server" /><br />
            <br />
            &nbsp;<asp:Button ID="Button1" runat="server" Text="上传" OnClick="Button1_Click" /></div>
          
        </form>
    </body>
    </html>
    default.aspx.csusing 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.OleDb;
    using System.IO;public partial class _Default : System.Web.UI.Page 
    ...{
        protected void Page_Load(object sender, EventArgs e)
        ...{    }
        protected void Button1_Click(object sender, EventArgs e)
        ...{
            try
            ...{
                if (FileUpload1.HasFile)
                ...{
                    if (IsAllowedExtension(this.FileUpload1))
                    ...{
                        //取得上传文件的大小
                        int FileLen = FileUpload1.PostedFile.ContentLength;                    Byte[] FileData = new Byte[FileLen];                    //创建访问客户端上传文件的对象
                        HttpPostedFile hp = FileUpload1.PostedFile;                    //创建数据流对象
                        Stream sr = hp.InputStream;                    //将图片数据放到FileData数组对象实例中,0代表数组指针的起始位置,FileLen代表指针的结束位置
                        sr.Read(FileData, 0, FileLen);                    OleDbConnection conn = new OleDbConnection("Provider = Microsoft.JET.OleDB.4.0;Data Source = " + Server.MapPath("mydata.mdb"));
                        conn.Open();
                        OleDbCommand cmd = new OleDbCommand("insert into table_img(img) values(?)", conn);                    //存储过程插入到数据库中
                        OleDbParameter para = new OleDbParameter("?", OleDbType.Binary);
                        para.Value = FileData;
                        cmd.Parameters.Add(para);
                        cmd.ExecuteNonQuery();                    //弹出上传成功的提示
                        Response.Write("<script languge = ‘javascript‘ type = ‘text/javascript‘>alert(‘上传成功‘);</script>");                    //关闭数据库连接
                        conn.Close();                }
                    else
                    ...{
                        Response.Write("<script languge = ‘javascript‘ type = ‘text/javascript‘>alert(‘上传文件格式不对,只允许上传jpg和gif格式的文件‘);</script>");
                    }
                }
                else
                ...{
                    Response.Write("<script language = ‘javascript‘ type = ‘text/javascript‘>alert(‘请选择上传文件‘);</script>");
                }
            }
            catch
            ...{
            }
        }
      

  3.   

      if (this.imgUrl1.PostedFile.FileName != null)
            {
                string descirption = txtDes.Text;//文件的简要描述
                string photoName = imgUrl1.PostedFile.FileName;//获取初始文件名
                
                int i = photoName.LastIndexOf(".");//取得文件名中最后一个“.”的索引
                string newext = photoName.Substring(i);//获取文件扩展名
                if (newext != ".gif" && newext != ".jpg" && newext != ".jpeg" && newext != ".bmp" && newext != ".png")
                {
                    this.spFile.Visible = true;
                    this.spFile.InnerHtml = "*文件格式不正确";
                    //Response.Write("文件格式不正确");
                    //Response.End();
                }
                else 
                {
                    DateTime date = Convert.ToDateTime(txtDate.Text);                string length = (Convert.ToDouble(imgUrl1.PostedFile.ContentLength) / 1024 ).ToString("f2")+"KB";//文件的大小
                    
                    //string photoName2 = now.Millisecond.ToString() + "_" +
                    //    imgUrl.PostedFile.ContentLength.ToString() +
                    //    newext;//重新为文件命名,时间毫秒部门+文件大小+扩展名
                    string imageurl = "Web/PersonInSanli/" + upLoad.UpImage(this.Page, this.imgUrl1);//文件路径
                    if (imageurl != "Web/PersonInSanli/")
                    {
                        string serverPath = Server.MapPath(@"~\") + imageurl;
                        imgUrl1.PostedFile.SaveAs(serverPath);
                    }
                    //Convert.ToDateTime(date)
                    bool bl = Company.photoAdd(photoName, imageurl, date, descirption, length);
                    this.Response.Redirect("InSanli.aspx");                //myFile.PostedFile.SaveAs(Server.MapPath("photos" + photoName2));//保存文件到路径,用
                    //Server.MapPath()取当前文件的绝对目录,在asp.net里"\"必须用""代替
                }
                
            }
    刚做的上传图片
      

  4.   

    上传图片:Imports System.Data.SqlClientPartial Class Add_ScrewCAP
        Inherits System.Web.UI.Page    Dim sql As New standsql
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load If Session("m_id") = 0 Or Session("m_id") = Nothing Then
    Session("Url") = My.Request.Url.ToString
    'Response.Redirect("Login.aspx?sysmesg=請先登入會員")
    Response.Redirect("login.aspx?sysmesg=7")
    End If
    End Sub    Protected Sub btn_add_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btn_add.Click
            Dim path As String = Server.MapPath("~/CAP/")
            Dim FileName As String = CStr(System.IO.Path.GetFileName(fud.PostedFile.FileName))
            Dim FilePath As String = CStr(path & FileName)        If Me.tb_partnum.Text = "" Then My.SysEIP.WebForm.CientMsgBox("請輸入料號", Me) : Exit Sub
    'If Me.tb_specs.Text = "" Then My.SysEIP.WebForm.CientMsgBox("請輸入規格", Me) : Exit Sub
            If Me.type.SelectedValue = "請選擇" Then My.SysEIP.WebForm.CientMsgBox("請選擇類型", Me) : Exit Sub
            If Me.fud.HasFile = False Then My.SysEIP.WebForm.CientMsgBox("請加入檔案", Me) : Exit Sub
            If Me.fud.PostedFile.ContentLength > 307200 Then My.SysEIP.WebForm.CientMsgBox("圖片大小不能超過300K", Me) : Exit Sub If Me.fud.HasFile = True Then sql.conndb(1)
    Dim str As String = Nothing
    str = "insert into Screw_Cap (type,partnum,material,specs,photoname)"
    str += "values (@type,@partnum,@material,@specs,@photoname)" sql.cmd.CommandText = str
    sql.cmd.Parameters.Clear()
    sql.cmd.Parameters.AddWithValue("@type", CStr(Me.type.SelectedValue))
    sql.cmd.Parameters.AddWithValue("@partnum", CStr(Me.tb_partnum.Text.Trim))
    sql.cmd.Parameters.AddWithValue("@material", CStr(Me.tb_material.Text.Trim))
    sql.cmd.Parameters.AddWithValue("@specs", CStr(Me.tb_specs.Text.Trim))
    'sql.cmd.Parameters.AddWithValue("photo",)
    sql.cmd.Parameters.AddWithValue("@photoname", CStr(FileName))
    sql.cmd.ExecuteNonQuery() sql.conndb(0)
    If Not sql.conn Is Nothing Then sql.conn.Close()
    Me.fud.PostedFile.SaveAs(FilePath)
    'Response.Redirect("message.aspx?sysmesg=文件上傳成功")
    My.SysEIP.WebForm.CientMsgBox("新增記錄成功", Me)
    cleardata() End If
    End Sub Private Sub cleardata()
    Me.tb_partnum.Text = ""
    Me.tb_material.Text = ""
    Me.tb_specs.Text = ""
    Me.type.SelectedValue = "請選擇"
    End Sub
    End Class
      

  5.   

    打开图片:用gridview 的Hyperlink来打开图片