需求说明:
实际项目中,有必要上传附件(包括图片、文档、解压文件等)对数据库数据完善,这里实现的功能就是,上传附件到数据库,然后从数据读出来之后,可以“点击下载”之前上传的附件内容。
asp.net代码如下:
//用FileUpload控件,上传附件之后,导入数据库操作 protected void btnUp_Click(object sender, EventArgs e) { DbSql db = new DbSql(); //数据操作类 string fileName = ""; string fielurl = ""; if (filePhoto.HasFile) { fileName = filePhoto.FileName; if (!ValidateFileType(fileName)) //上传文件类型判断 { Response.Write("<script>alert('不支持文件!')</script>"); return; } fileName = fileName.Replace(":", "_").Replace(" ", "_").Replace("\\", "_").Replace("/", "_"); fileName = DateTime.Now.Ticks.ToString() + "_" + fileName; filePhoto.SaveAs(Server.MapPath("~/upload/" + fileName)); string strr = "~/upload/" + fileName + ""; fielurl = "<a href=../MidDownFile.aspx?fileUrl=" + Server.UrlEncode(strr) + ">点击下载</a>";//用MidDownFile页面,处理对上传文件的下载 db.ExecSql("insert into fileUp(t_content) values('" + fielurl + "')"); //数据操作类中的ExecSql方法,执行Sql语句 } DataTable dt = db.FillDt("select * from fileUp"); labFile.Text = dt.Rows[0]["t_content"].ToString() //显示数据库中的第一条,用于测试 }下面是判断上传文件类型的一个使用方法
#region 上传文件类型判断 protected readonly static List<string> VALID_FILE_TYPES = new List<string> { "jpg", "bmp", "gif", "jpeg", "png", "rar", "txt", "doc", "docx" }; protected static bool ValidateFileType(string fileName) { string fileType = String.Empty; int lastDotIndex = fileName.LastIndexOf("."); if (lastDotIndex >= 0) { fileType = fileName.Substring(lastDotIndex + 1).ToLower(); } if (VALID_FILE_TYPES.Contains(fileType)) { return true; } else { return false; } } #endregion接下来是MidDownFile.aspx页面处理对上传文件的下载
protected void Page_Load(object sender, EventArgs e) { string fileName = Server.UrlDecode(Request.QueryString["fileUrl"]); WriteF(fileName); } public void WriteF(string fileName) { if (System.IO.File.Exists(Server.MapPath(fileName))) { Response.ContentType = "application/x-zip-compressed"; Response.AddHeader("Content-Disposition", "attachment;filename=" + System.IO.Path.GetFileName(fileName) + ""); string filename = Server.MapPath(fileName); Response.TransmitFile(filename); } else { Response.Write("文件不存在!"); } }