如何把文件存放到数据库中
展开全部
发给你一个上传图片并把它存入数据库的例子。
1.前台<table cellpadding="0" cellspacing="0"
<tr<td colspan="2"</td</tr<tr<td<asp:Label ID="Label1" runat="server" Font-Size="9pt" Text="选择文件"</asp:Label</td
<td align="left"<asp:FileUpload ID="FileUpload1" runat="server" Font-Size="9pt" /</td</tr<tr<td</td
<td align="left"
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="保存"/</td</tr<tr<td</td
<td align="left"
<asp:Label ID="Label3" runat="server" Font-Size="9pt" Width="216px"</asp:Label</td</tr</table
2.后台using System.IO;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page{protected void Button1_Click(object sender, EventArgs e){try{if (this.FileUpload1.PostedFile.FileName != ""){string ImgPath = FileUpload1.PostedFile.FileName;
string ImgName = ImgPath.Substring(ImgPath.LastIndexOf("\\") + 1);
string ImgExtend = ImgPath.Substring(ImgPath.LastIndexOf(".") + 1);
int FileLen = this.FileUpload1.PostedFile.ContentLength;
Byte[] FileData = new Byte[FileLen];
HttpPostedFile hp = FileUpload1.PostedFile;
Stream sr = hp.InputStream;
sr.Read(FileData, 0, FileLen);
SqlConnection con = new SqlConnection("server=(local);user id=sa;pwd=;database=db_07");
con.Open();
SqlCommand com = new SqlCommand("INSERT INTO tb_08 (name) VALUES (@imgdata)", con);
com.Parameters.Add("@imgdata", SqlDbType.Image);
com.Parameters["@imgdata"].Value = FileData;
Label3.Text = "保存成功!";}else{Label3.Text = "请选择文件!";}}catch (Exception error){Label3.Text = "处理失败!原因为:" + error.ToString();}}}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询