首页 > 代码库 > 在数据库中 保存和获取各种文件
在数据库中 保存和获取各种文件
http://www.aspsnippets.com/Articles/How-to-save-insert-Image-in-Database-in-ASPNet-using-C-and-VBNet.aspx
1.创建数据库--各字段如下图所示
注:Name:文件名
ContentType:文件的类型 (.doc .txt)
Data:以二进制的存储的数据
2.添加文件上传控件和上传按钮
<asp:FileUpload ID="FileUpload1" runat="server" /> <asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="btnUpload_Click" /><br /> <asp:Label ID="lblMessage" runat="server" Text="" Font-Names = "Arial"></asp:Label>
3.添加上传文件事件
protected void btnUpload_Click(object sender, EventArgs e) { //获取上传的文件 string filePath = FileUpload1.PostedFile.FileName; //获取上传文件名 string filename = Path.GetFileName(filePath); //获取文件按的后缀名 string ext = Path.GetExtension(filename); string contenttype = String.Empty; //根据后缀名设置文件类型 switch (ext) { case ".doc": contenttype = "application/vnd.ms-word"; break; case ".docx": contenttype = "application/vnd.ms-word"; break; case ".xls": contenttype = "application/vnd.ms-excel"; break; case ".xlsx": contenttype = "application/vnd.ms-excel"; break; case ".jpg": contenttype = "image/jpg"; break; case ".png": contenttype = "image/png"; break; case ".gif": contenttype = "image/gif"; break; case ".pdf": contenttype = "application/pdf"; break; } if (contenttype != String.Empty) { Stream fs = FileUpload1.PostedFile.InputStream; BinaryReader br = new BinaryReader(fs); Byte[] bytes = br.ReadBytes((Int32)fs.Length); //insert the file into database string strQuery = "insert into FileSaves(Name, ContentType, Data)" +"values (@Name, @ContentType, @Data)"; SqlCommand cmd = new SqlCommand(strQuery); cmd.Parameters.Add("@Name", SqlDbType.VarChar).Value =http://www.mamicode.com/ filename; cmd.Parameters.Add("@ContentType", SqlDbType.VarChar).Value = contenttype; cmd.Parameters.Add("@Data", SqlDbType.Binary).Value =http://www.mamicode.com/ bytes; InsertUpdateData(cmd); lblMessage.ForeColor = System.Drawing.Color.Green; lblMessage.Text = "File Uploaded Successfully"; } else { lblMessage.ForeColor = System.Drawing.Color.Red; lblMessage.Text = "File format not recognised." +" Upload Image/Word/PDF/Excel formats"; } }
4.根据查询字符串判断文件是否上传成功
private Boolean InsertUpdateData(SqlCommand cmd) { String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["DemosDatabaseConnectionString"].ConnectionString; SqlConnection con = new SqlConnection(strConnString); cmd.CommandType = CommandType.Text; cmd.Connection = con; try { con.Open(); cmd.ExecuteNonQuery(); return true; } catch (Exception ex) { Response.Write(ex.Message); return false; } finally { con.Close(); con.Dispose(); } }
在数据库中 保存和获取各种文件
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。