使用ASP.NET上传多个文件到数据库
2009-03-20 06:45
363 查看
如果仅仅是上传一个文件,最好是使用FileUpload控件, 可以使用FileUpload1.FileContent.Length得到文件大小, FileUpload1.FileBytes得到其字节数组, 代码略.
如果要上传多个文件, 其客户端代码与使用ASP.NET上传多个文件到服务器基本相同, 本例中加入了下载的示例代码。
效果图如下:
数据库脚本
页面代码:MutlileFileUploadToDB.aspx
后台代码:MutlileFileUploadToDB.aspx.cs
如果要上传多个文件, 其客户端代码与使用ASP.NET上传多个文件到服务器基本相同, 本例中加入了下载的示例代码。
效果图如下:
数据库脚本
create database FileDB go use FileDB go create table dbo.Files ( id int identity primary key ,FileName varchar(50) not null ,FileSize int not null ,FileData image not null --,UpTime DateTime default getdate() --,DownLoadTimes int default 0 ) go
页面代码:MutlileFileUploadToDB.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="MutlileFileUploadToDB.aspx.cs" Inherits="MutlileFileUploadToDB" %> <!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> <title>多文件上传到数据库Demo</title> <link href="css/writemail.css" mce_href="css/writemail.css" rel="stylesheet" type="text/css" /> <mce:script type="text/javascript"><!-- var MAXFILES = 5; //文件计数器 var fileCount = 0; function addAttach(noAlert) { if (fileCount >= MAXFILES && !noAlert) { alert("最多只能添加" + MAXFILES + "个附件!"); return; } var fileSectionDiv = document.getElementById("files"); var fileItemDiv = document.createElement("div"); fileCount++; var content = "<input type='file' onchange='return addAttach(true);' name='fileUpload'" + fileCount + "> <a href="#" mce_href="#" onclick='return delAttach(/"" + fileCount + "/")' class='delete_attach' >移除附件</a>"; fileItemDiv.id = "fileItemDiv" + fileCount; fileItemDiv.innerHTML = content; fileSectionDiv.appendChild(fileItemDiv); return false; } function delAttach(fileIndex) { var fileSectionDiv = document.getElementById("files"); var fileItemDiv = document.getElementById("fileItemDiv" + fileIndex); fileSectionDiv.removeChild(fileItemDiv); return false; } // --></mce:script> </head> <body> <form id="form1" runat="server" > <div> <a id="addAttach_a" onclick="return addAttach(false);" href="#" mce_href="#" class="add_attach">添加附件</a> <div id="files"></div> <asp:Button ID="btnSend" runat="server" Text="发送" onclick="btnSend_Click" /> <asp:GridView ID="gvwFiles" runat="server" AutoGenerateColumns="False" DataKeyNames="id" DataSourceID="sdsFiles" onrowcommand="gvwFiles_RowCommand"> <Columns> <asp:BoundField DataField="FileName" HeaderText="FileName" SortExpression="FileName" /> <asp:BoundField DataField="FileSize" HeaderText="FileSize" SortExpression="FileSize" /> <asp:TemplateField> <ItemTemplate> <asp:LinkButton ID="lbtnDownload" runat="server" CommandName="download" CommandArgument='<%#Eval("FileName") %>'>下载</asp:LinkButton> </ItemTemplate> </asp:TemplateField> </Columns> </asp:GridView> <asp:SqlDataSource ID="sdsFiles" runat="server" ConnectionString="<%$ ConnectionStrings:FileDBConnectionString %>" DataSourceMode="DataReader" ProviderName="<%$ ConnectionStrings:FileDBConnectionString.ProviderName %>" SelectCommand="SELECT [id], [FileName], [FileSize] FROM [Files]"> </asp:SqlDataSource> </div> </form> </body> </html>
后台代码:MutlileFileUploadToDB.aspx.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.IO; using System.Data.SqlClient; public partial class MutlileFileUploadToDB : System.Web.UI.Page { protected void Page_Load(object sender, System.EventArgs e) { //告诉表单如何格式化文件信息 Page.Form.Enctype = "multipart/form-data"; } protected void btnSend_Click(object sender, EventArgs e) { for (int index = 0; index < Request.Files.Count; index++) { HttpPostedFile file = Request.Files[index]; if (!string.IsNullOrEmpty(file.FileName)) { byte[] fileBytes = new byte[file.ContentLength]; file.InputStream.Read(fileBytes, 0, file.ContentLength); using (SqlConnection cn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["FileDBConnectionString"].ConnectionString)) { SqlCommand cmd = new SqlCommand("insert into Files(FileName, FileSize, FileData) values(@fileName, @fileSize, @fileData)", cn); cmd.Parameters.AddWithValue("@fileName", Path.GetFileName(file.FileName)); cmd.Parameters.AddWithValue("@fileSize", file.ContentLength); cmd.Parameters.AddWithValue("@FileData", fileBytes); cn.Open(); cmd.ExecuteNonQuery(); } } } gvwFiles.DataBind(); } protected void gvwFiles_RowCommand(object sender, GridViewCommandEventArgs e) { if (e.CommandName == "download") { byte[] fileData = null; using (SqlConnection cn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["FileDBConnectionString"].ConnectionString)) { SqlCommand cmd = new SqlCommand("select FileData from files where id = @id", cn); int index = ((e.CommandSource as LinkButton).NamingContainer as GridViewRow).RowIndex; cmd.Parameters.AddWithValue("@id", gvwFiles.DataKeys[index].Value); cn.Open(); fileData = cmd.ExecuteScalar() as byte[]; } if (fileData == null) { Response.StatusCode = 404; } else { //使用Content-Disposition会有些缺点,在不同的浏览器中文件名显示有些不正常,如果用FireFox就无须编码 Response.AddHeader("Content-Disposition", "attachment; filename=/"" + HttpUtility.UrlEncode(e.CommandArgument.ToString(), System.Text.Encoding.UTF8) + "/""); Response.BinaryWrite(fileData); } Response.End(); } } }
相关文章推荐
- 使用ASP.NET上传多个文件到数据库
- ASP.NET 使用js插件出现上传较大文件失败的解决方法(ajaxfileupload.js第一弹)
- ASP.NET中上传文件到数据库
- ASP.NET中上传文件到数据库
- ASP.NET使用SWFUpload上传大文件教学(源码)
- Asp.Net上传文件示例(保存文件路径到数据库)
- Asp.NET使用HTML控件上传文件
- ASP.NET使用FileUpload上传文件
- asp.net ajax AjaxFileUpload使用 多文件上传
- ASP.NET上传下载文件示例,使用webClient实现
- asp.net文件上传用到html的file控件,在使用母版页Master,更改form的Enctype=multipart/form-data的方法
- 解决asp.net中使用FckEditor上传文件,中文名称乱码的问题
- 如何在ASP.NET中上传文件到数据库
- 解决asp.net中使用FckEditor上传文件,中文名称乱码的问题
- [收藏]ASP.NET中上传文件到数据库
- ASP.NET插件uploadify批量上传文件完整使用教程
- asp.net(C#) 上传Execl文件 并插入数据到数据库实例
- ASP.NET 2.0使用FileUpload控件上传文件示例
- JQuery.uploadify 上传文件插件的使用详解 for ASP.NET
- ASP.NET MVC使用Uploadify上传文件