网上类似上传并保存至数据库的文章不少,不知道是我环境不行,还是怎么得,总是有问题,而且也没同时成缩略图的,经过二天的调试,终于搞定,主要代码如下:
数据库结构
Images(ID int, Photo varbinary(MAX) , smallPhoto varbinary(MAX) )
前台代码
<form id="form1" runat="server" enctype="multipart/form-data">
<asp:FileUpload ID="imgPath" runat="server" Width="300px">
</form>
(注:多个FileUpload可使用js操作,js代码略)
后台代码
if (HttpContext.Current.Request.Files != null) { HttpFileCollection _files = HttpContext.Current.Request.Files; for (int i = 0; i < _files.Count; i++) { if (_files[i] != null && _files[i].ContentLength != 0) { ///处理上载的文件流信息。 byte[] b = new byte[_files[i].ContentLength]; Stream fs = (Stream)_files[i].InputStream; fs.Read(b, 0, _files[i].ContentLength); MemoryStream m = new MemoryStream(); Bitmap img = new Bitmap(fs); //产生缩略图并保存 img.GetThumbnailImage(110, 135, null, new IntPtr()).Save(m, System.Drawing.Imaging.ImageFormat.Jpeg); if (b.Length > 0 && (int)m.Length > 0) { string sql = "INSERT INTO Images(Photo,smallPhoto) VALUES(@Photo,@smallPhoto)"; SqlParameter[] parameters = { new SqlParameter("@Photo", SqlDbType.VarBinary), new SqlParameter("@smallPhoto", SqlDbType.VarBinary) }; parameters[0].Value = b; parameters[1].Value = m.ToArray(); (存入数据库代码略) } } } }
目前我只测试了上传200K的图片没有任何问题,具体最大图片能到多少K,需要查询MSDN了
需要注意的是,我试过Image的数据类型,怎么都不行,使用varbinary(MAX)就没问题