ASP.NET上传文件到数据库(转贴)

一、上传到数据库。

(sqlserver 
为例 )
存储文件的数据库中的字段为  jimage ,类型为  image
在代码中定义类型为  byte[] 的一个变量  buf ,在上传组件的  PostFile  中,从它的  InputStream 读出字节数组,将  buf  赋给数据字段  jimage  就可以了。
int len = this.File1.PostedFile.ContentLength; 
byte[] buf = new byte[len]; 
  
Stream i = this.File1.PostedFile.InputStream; 
i.Read(buf,0,buf.Length); 
news.jimage=buf;
//news 
为新闻类, jimage  为它的图片属性,即对应表中的  image
i.Close();
显示图像:
图片的显示也很简单,在  Persister  中注意一下:
SqlDataReader reader=SqlHelper.ExecuteReader("select jimage from news");
 
if( reader.Read() )
 {
 news.jimage=(byte[])reader["jimage"];
}
reader.Close();
得到  byte[] 的内容,要显示也比较简单,在  Page_Load() 方法中加两句话即可:
Response.ContentType="image/jpeg";
Response.BinaryWrite(ti.content);
这样就可以输出图像了,如果想对图像做一点调整 , 如旋转,转换格式、获得图片格式(是  jpg 还是 gif ),请参考下面代码:
//
同样,声明输出不是  HTML  而是  image
 Response.ContentType="image/jpeg";
 
 //
 byte[] 得到一个  image  对象
 System.Drawing.Image bmap = Bitmap.FromStream(new MemoryStream(ti.content));
 //
操作一下这个图像
  bmap.RotateFlip(RotateFlipType.Rotate180FlipY);
  //
输出到页面上
 bmap.Save(Response.OutputStream,System.Drawing.Imaging.ImageFormat.Jpeg);
//
释放 image
bmap.Dispose();
要显示图片在某一个  image  控件上,可采用下法:
要显示图片的位置放一个  image  控件然后将它的  src  指向这个页面就行了!
例如:
页面: ViewImage.aspx
<%@Import Namespace="System.IO"%>
<%@Import Namespace="System.Data"%>
<%@Import Namespace="System.Data.SqlClient"%>
<%@ Page Language="C#" Debug="True" %>
<script runat="server">
private void Page_Load(Object sender, System.EventArgs e)
{
string imgid =Request.QueryString["UserID"];
string connstr="data source=(local);initial catalog=Test;integrated security=SSPI;persist security info=True;packet size=4096";
string sql="SELECT IMGTITLE,imgdata, imgtype FROM ImageStore WHERE id = '"
imgid  "'";


SqlConnection connection = new SqlConnection(connstr);
SqlCommand command = new SqlCommand(sql, connection);
connection.Open();
SqlDataReader dr = command.ExecuteReader();

if(dr.Read())
{
Response.ContentType = dr["imgtype"].ToString();
Response.BinaryWrite( (byte[]) dr["imgdata"] );
Response.Write(dr["IMGTITLE"].ToString());
}
connection.Close();
}
</script>

显示图片的页面上放一个  image  控件  imgZYF   在后代码中写:
imgZYF.ImageUrl =“ViewImage.aspx?UserID=" +userId
二、上传到服务器的磁盘:

   页面文件 :upload01.aspx
<%@ Page language="c#" Codebehind="upload01.aspx.cs" AutoEventWireup="false" Inherits="upload01.upload01" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
 <HEAD>
  <title>
上传到磁盘 </title>
 </HEAD>
 <body>
  <form id="Form1" method="post" runat="server">
   <TABLE height="300" cellSpacing="1" cellPadding="1" width="500" border="0" class="bigtable-bj"
    align="center">
    <TR>
     <TD><FONTFONT-SIZE: 9pt;">宋体
">
       <TABLE id="Table1" style="WIDTH: 384px; HEIGHT: 54px" cellSpacing="1" cellPadding="1" width="384"
        border="0" align="center">
        <TR>
         <TD>
选择文件: </TD>
         <TD><INPUT type="file" id="myfile" runat="server"></TD>
        </TR>
        <TR>
         <TD style="HEIGHT: 21px">
输入备注: </TD>
         <TD style="HEIGHT: 21px">
          <asp:TextBox id="TextBox1" runat="server"></asp:TextBox></TD>
        </TR>
        <TR>
         <TD></TD>
         <TD><INPUT type="button" value="
上传文件 " runat="server" id="Button1" name="Button1">&nbsp;
          <INPUT type="submit" value="
清空选择 "></TD>
        </TR>
       </TABLE>
      </FONT>
     </TD>
    </TR>
   </TABLE>
  </form>
 </body>
</HTML>

  
后置代码 :upload01.aspx
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
namespace upload01
{
 public class upload01 : System.Web.UI.Page
 {
  protected System.Web.UI.HtmlControls.HtmlInputButton Button1;
  protected System.Web.UI.WebControls.TextBox TextBox1;
  protected System.Web.UI.HtmlControls.HtmlInputFile myfile;
 
  private void Page_Load(object sender, System.EventArgs e)
  {
  

  }
 
  private void Button1_ServerClick(object sender, System.EventArgs e)
  {
   //
取得客户端路径及文件名
   string str=myfile.PostedFile.FileName;
   //
取得文件类型,如 .jpg
   string filename2=str.Substring(str.LastIndexOf(".")).ToString().Trim();
     //
取得文件大小,单位 K
   double filesize=myfile.PostedFile.ContentLength/1024.00;
   //
以时间刻度定义文件名
   string filename1=DateTime.Now.Ticks.ToString();
    myfile.PostedFile.SaveAs(Server.MapPath("/upload01/"+filename1+filename2));
   //
将文件名及相关信息存到数据库中
  }
 }
}
    将文件上传到磁盘中,在表中将文件地址或路径记录下来,这样就可以在后面的程序来引用了。

  转载于:http://www.evget.com/zh-CN/article/2272/default.aspx

   我是这样上传的:
       其中:NewInsertCommand是一个存储过程,只有一个参数@image

     protected   void  Button1_Click( object  sender, EventArgs e)
    
{
        
if (File1.HasFile)
        
{
            
int len = this.File1.PostedFile.ContentLength;
            
byte[] buf = new byte[len];
            Stream i 
= this.File1.PostedFile.InputStream;
            i.Read(buf, 
0, buf.Length);
            SqlConnection con 
= new SqlConnection(ConfigurationManager.ConnectionStrings["drop"].ConnectionString);
            SqlCommand cmd 
= new SqlCommand("NewInsertCommand", con);
            cmd.CommandType 
= CommandType.StoredProcedure;
            cmd.Connection 
= con;
            con.Open();
            cmd.Parameters.AddWithValue(
"@image", buf);
            cmd.ExecuteNonQuery();
            i.Close();
            con.Close();
        }

    }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值