一:上传 (把文件上传到数据库中image类型的字段中去了)
public void upload()
{
Stream objFs;
objFs = uploadFile.PostedFile.InputStream;
BinaryReader objBr = new BinaryReader(objFs);
byte[] bytFile = objBr.ReadBytes((int)objFs.Length);
//文件内容
model.DocContent = bytFile;
//归档单位
model.FilingUnit = this.ddlFilingUnit.SelectedValue.ToString().Trim();
//归档号
model.FilingNo = this.txtFilingNo.Value.Trim();
//文件名(后台控制:用户留空时则录入原文件名)
if(this.txtDocName.Value.ToString().Trim() == "" || this.txtDocName.Value.ToString().Trim() == null)
{
int start = uploadFile.PostedFile.FileName.LastIndexOf("\\");
int end = uploadFile.PostedFile.FileName.LastIndexOf(".");
model.DocName = uploadFile.PostedFile.FileName.Substring(start+1, end-start-1);
}
else
{
model.DocName = this.txtDocName.Value.Trim();
}
//获取文件后缀名:1、获取初始文件名
string tempStr = this.uploadFile.PostedFile.FileName.ToString();
//2、取得文件名中最后一个"."的索引
int i = tempStr.LastIndexOf(".") + 1;
//3、获取文件扩展名并转为小写
model.DocSuffix = tempStr.Substring(i).ToLower();
//文件大小
model.DocSize = this.uploadFile.PostedFile.ContentLength;
//MIME类型
model.ContentType = this.uploadFile.PostedFile.ContentType;
new RecordsMgtBll().AddDoc(model);
}
二:下载 新建一个用于输出文件的页面(点击下载的时候就跳转到此页面并且传要下载的文件ID)
private void Page_Load(object sender, System.EventArgs e)
{
if(!Page.IsPostBack)
{
_DocId = Request.QueryString["DocId"];
ViewState["_DocId"] = _DocId;
}
string sql="SELECT * FROM b_bridge_doc WHERE DocId='" + ViewState["_DocId"].ToString() + "' ";
SqlConnection connection = new SqlConnection(System.Configuration.ConfigurationSettings.
AppSettings["SqlServerConnectionString"]);
SqlCommand command = new SqlCommand(sql, connection);
connection.Open();
SqlDataReader dr = command.ExecuteReader();
if(dr.Read())
{
Response.Clear();
Response.AddHeader("Content-Type", dr["ContentType"].ToString());
string fileName = dr["DocName"].ToString() + "." + dr["DocSuffix"].ToString();
Response.AddHeader("Content-Disposition", "attachment; filename=" +
HttpUtility.UrlEncode( fileName));
Response.Flush();
Response.BinaryWrite((byte[])dr["DocContent"]);
}
dr.Close();
connection.Close();
}