日期:2014-05-19  浏览次数:20616 次

急求,文件如何上传保存在数据库中,同时,如何从数据库中读取供用户下载
文件如何上传保存在数据库中,同时,如何从数据库中读取供用户下载
asp.net技术如何实现啊?
具体如下:
用户在aspx页面直接上传文件保存到数据库中,
同时如何在aspx页面从数据库中读取文件供用户下载;


------解决方案--------------------
文件一定要保存在数据库中吗?
------解决方案--------------------
ASP.NET中上传文件到数据库
http://blog.sina.com.cn/u/53a8153e0100059a
------解决方案--------------------
读取

http://www.z6688.com/info/48025-1.htm
------解决方案--------------------
分两步,先传文件到服务器,服务器再保存到数据库;下载一样!
------解决方案--------------------
建议不要放在数据库内!性能消耗比较大
------解决方案--------------------
数据库中最好只存文件名
------解决方案--------------------
(一).上传
1.
<INPUT id= "WebFile " style= "WIDTH: 490px; HEIGHT: 22px " type= "file " size= "62 " name= "WebFile " runat= "server ">
protected System.Web.UI.HtmlControls.HtmlInputFile WebFile;
文件上传参考代码:
/// <summary>
/// 文件上传
/// </summary>
/// <param name= "sender "> </param>
/// <param name= "e "> </param>
private void BtnUpload_Click(object sender, System.EventArgs e)
{
if(WebFile.PostedFile.FileName== " ")
{
Info.Text= "请先选择要上传的文件 ";
return;
}

try
{
char[] spliter = { '\\ '};
string [] FileName = WebFile.PostedFile.FileName.Split(spliter,10);

string FullPath = CurrentPath + @ "\ " + FileName[FileName.Length-1]; //生成完整文件名
WebFile.PostedFile.SaveAs(FullPath); //保存文件
LoadDir(CurrentPath); //重新载入当前目录
}
catch
{
Info.Text= "上传文件失败,请与管理员联系 ";
}
}

2.
http://www.gdcic.net/dotnetBank/ViewContent.aspx?artid=000000000186

(二).下载

1. C#:
/// <summary>
/// 文件下载
/// </summary>
/// <param name= "FullFileName "> </param>
private void FileDownload(string FullFileName)
{
FileInfo DownloadFile = new FileInfo(FullFileName);
Response.Clear();
Response.ClearHeaders();
Response.Buffer=false;
Response.ContentType= "application/octet-stream ";
Response.AppendHeader( "Content-Disposition ", "attachment;filename= " +HttpUtility.UrlEncode(DownloadFile.FullName,System.Text.Encoding.UTF8));
Response.AppendHeader( "Content-Length ",DownloadFile.Length.ToString());
Response.WriteFile(DownloadFile.FullName);
Response.Flush();
Response.End();
}

------解决方案--------------------
实际上传就是将文件转化为流存入数据库,如果是sql数据库的话该字段需要设置为image类型,比如:
public byte[] ConvertFileToBytes(HttpPostedFile oFile)
{
Stream sm = oFile.InputStream;
byte[] bytes = new byte[oFile.ContentLength];
sm.Read(bytes, 0, oFile.ContentLength);

return bytes;
}
------解决方案--------------------
string connstr= "server=(local);uid=sa;password=sa;database=news ";
SqlConnection conn=new SqlConnection(connstr);
conn.Open();
SqlCommand cmd=new SqlCommand();
cmd.CommandText= "select top 1 * from image ";
cmd.Connection=conn;