62,041
社区成员
发帖
与我相关
我的任务
分享
这里是我保存文件转为二进制流存入数据库的方法
if (this.File1.PostedFile.FileName != "")
{
//得到提交的文件
Stream fileDataStream = this.File1.PostedFile.InputStream;
//得到文件大小
int fileLength = this.File1.PostedFile.ContentLength;
//创建数组
byte[] fileData = new byte[fileLength];
//把文件流填充到数组
fileDataStream.Read(fileData, 0, fileLength);
//获取上传文件的完整路径以及文件名
string FullName = this.File1.PostedFile.FileName.ToString();
//得到文件名字
string fileTitle = FullName.Substring(FullName.LastIndexOf("\\") + 1);
//得到文件类型
string fileType = FullName.Substring(FullName.LastIndexOf(".") + 1);
-------------------------插入数据库的操作就没必要贴了-----------------------------------------------------
}
File.WriteAllBytes
string imagename = "";
try
{
con.Open();
SqlCommand com = new SqlCommand("select name from tb_17 where id="+DropDownList1.Text+"", con);
SqlDataReader dr = com.ExecuteReader();
dr.Read();
MemoryStream ms = new MemoryStream((Byte[])dr["name"]);
Bitmap image = new Bitmap(ms);
string filepath = Server.MapPath("Files/");
DirectoryInfo dir = new DirectoryInfo(filepath);
FileInfo[] filecount = dir.GetFiles();
int i = filecount.Length;
imagename = filepath + ((i + 1) + ".jpg");
image.Save(imagename);
dr.Close();
Image1.ImageUrl = "Files/" + ((i + 1) + ".jpg");
}
finally
{
con.Close();
}
//二进制与图片互转
Image aa = new Bitmap(@"E:\photo\tm.jpg");
System.IO.MemoryStream stream = new System.IO.MemoryStream();
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter
= new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); formatter.Serialize(stream, aa); //将图像序列化成二进制流
stream.Position = 0;
Image bb = (Image)formatter.Deserialize(stream); //将二进制流序列成Image
private void FileDown(string strPath)
{
System.IO.FileInfo file = new System.IO.FileInfo(strPath);
if (file.Exists)
{
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(file.FullName, System.Text.Encoding.UTF8));
Response.AddHeader("Content-Length", file.Length.ToString());
Response.ContentType = "application/octet-stream";
Response.Filter.Close();
Response.WriteFile(file.FullName);
Response.End();
}
else
{
ClientScript.RegisterStartupScript(GetType(), "", "<script language='javascript'>alert('文件不存在!');</script>");
}
}