一、文件(图片)保存到数据库
取出来显示:
二、文件(图片)保存到硬盘
方法一 /// <summary>
2 /// 下载文件
3 /// </summary>
4 /// <param name="filename">文件物理地址</param>
5 protected void DownloadFile(string filename)
6 {
7
8 string saveFileName = "test.xls";
9 int intStart = filename.LastIndexOf("\\")+1;
10 saveFileName = filename.Substring(intStart,filename.Length-intStart);
11
12 System.IO.FileInfo fi=new System.IO.FileInfo(filename);
13 string fileextname=fi.Extension;
14 string DEFAULT_CONTENT_TYPE = "application/unknown";
15 RegistryKey regkey,fileextkey;
16 string filecontenttype;
17 try
18 {
19 regkey=Registry.ClassesRoot;
20 fileextkey=regkey.OpenSubKey(fileextname);
21 filecontenttype=fileextkey.GetValue("Content Type",DEFAULT_CONTENT_TYPE).ToString();
22 }
23 catch
24 {
25 filecontenttype=DEFAULT_CONTENT_TYPE;
26 }
27
28
29 Response.Clear();
30 Response.Charset = "utf-8";
31 Response.Buffer= true;
32 this.EnableViewState = false;
33 Response.ContentEncoding = System.Text.Encoding.UTF8;
34
35 Response.AppendHeader("Content-Disposition","attachment;filename=" + saveFileName);
36 Response.ContentType=filecontenttype;
37
38 Response.WriteFile(filename);
39 Response.Flush();
40 Response.Close();
41
42 Response.End();
43 }
44
方法二
/// <summary>
2 /// 下载文件
3 /// </summary>
4 /// <param name="filename">文件物理地址</param>
5 protected void DownloadFile(string filename)
6 {
7 string saveFileName = "test.xls";
8 int intStart = filename.LastIndexOf("\\")+1;
9 saveFileName = filename.Substring(intStart,filename.Length-intStart);
10
11 Response.Clear();
12 Response.Charset = "utf-8";
13 Response.Buffer= true;
14 this.EnableViewState = false;
15 Response.ContentEncoding = System.Text.Encoding.UTF8;
16
17 Response.AppendHeader("Content-Disposition","attachment;filename=" + saveFileName);
18 Response.WriteFile(filename);
19 Response.Flush();
20 Response.Close();
21
22 Response.End();
23 }
2 /// 上传图片
3 /// </summary>
4 /// <param name="sender"></param>
5 /// <param name="e"></param>
6 /// <returns>操作结果</returns>
7 private bool ImageUpload(int nWidth,int nHeight)
8 {
9 System.Web.HttpFileCollection files = Request.Files;
10 System.Web.HttpPostedFile pf = files[0];
11 string sOldPath = pf.FileName.ToString();
12 int i = sOldPath.LastIndexOf("\\");
13 string sOldName = sOldPath.Substring(i+1,sOldPath.Length-i-1);
14 //"L"代表大图 && "S"代表缩略图
15 string sTimeNo = System.DateTime.Now.ToString("yyMMddHHmmss");
16 string sNewNameL = "L"+sTimeNo+"_"+sOldName;
17 string sNewNameS = sNewNameL.Replace("L"+sTimeNo,"S"+sTimeNo);
18 string sNewPathL = Server.MapPath("../images/uploadfiles/")+sNewNameL;
19 string sNewPathS = Server.MapPath("../images/uploadfiles/")+sNewNameS;
20 if(System.IO.File.Exists(sNewPathL)||System.IO.File.Exists(sNewPathS))
21 {
22 Page.RegisterStartupScript("FailToUpload","<script>alert('文件名已存在!');</script>");
23 return false;
24 }
25 else
26 {
27 pf.SaveAs(sNewPathL);//保存原图
28 string strContentType = pf.ContentType.ToString();
29 if(strContentType.IndexOf("image/")<0)
30 {
31 Page.RegisterStartupScript("KeyEro","<script>alert('无效的图片格式!');</script>");
32 return false;
33 }
34 else
35 {
36 this.GetThumbNail(sOldPath,strContentType,sNewPathS,nWidth, nHeight);
37 this.Image1.ImageUrl = sNewPathS;
38 return true;
39 }
40 }
41 }
42 /// <summary>
43 /// 生成缩略图
44 /// </summary>
45 /// <param name="FileName">待上传文件的完全限定名</param>
46 /// <param name="strContentType">待上传文件的内容类型</param>
47 /// <param name="path">路径</param>
48 /// <param name="nWidth">宽</param>
49 /// <param name="nHeight">高</param>
50 private void GetThumbNail(string FileName,string strContentType,string path,int nWidth,int nHeight)
51 {
52 System.Drawing.Image oImage;
53 oImage = System.Drawing.Image.FromFile(FileName);
54 oImage = oImage.GetThumbnailImage(nWidth,nHeight,null,IntPtr.Zero);
55 // MemoryStream ms = new MemoryStream();
56 // Response.ContentType = strContentType;
57 // oImage.Save(ms,strContentType);
58 oImage.Save(path,this.GetContenType(strContentType));
59 // ms.WriteTo(Response.OutputStream);
60 }
61 /// <summary>
62 /// 获取保存文件的格式
63 /// </summary>
64 /// <param name="strContentType">待上传文件的内容类型</param>
65 /// <returns>文件格式</returns>
66 private System.Drawing.Imaging.ImageFormat GetContenType(string strContentType)
67 {
68 //只写少数几种格式
69 if(strContentType.ToString().ToLower()== "image/bmp")
70 return System.Drawing.Imaging.ImageFormat.Bmp;
71 else if(strContentType.ToString().ToLower()== "image/gif")
72 return System.Drawing.Imaging.ImageFormat.Gif;
73 else
74 return System.Drawing.Imaging.ImageFormat.Jpeg;
75 }
//得到用户要上传的文件名
string strFilePathName = loFile.PostedFile.FileName;
string strFileName = Path.GetFileName(strFilePathName);
int FileLength = loFile.PostedFile.ContentLength;
if(FileLength<=0)
return;
try
{//上传文件
Byte[] FileByteArray = new Byte[FileLength]; //图象文件临时储存Byte数组
Stream StreamObject = loFile.PostedFile.InputStream; //建立数据流对像
//读取图象文件数据,FileByteArray为数据储存体,0为数据指针位置、FileLnegth为数据长度
StreamObject.Read(FileByteArray,0,FileLength);
//建立SQL Server链接
string strCon = System.Configuration.ConfigurationSettings.AppSettings["DSN"];
SqlConnection Con = new SqlConnection(strCon);
String SqlCmd = "INSERT INTO ImageStore (ImageData, ImageContentType, ImageDescription, ImageSize) VALUES (@Image, @ContentType, @ImageDescription, @ImageSize)";
SqlCommand CmdObj = new SqlCommand(SqlCmd, Con);
CmdObj.Parameters.Add("@Image",SqlDbType.Binary, FileLength).Value = FileByteArray;
CmdObj.Parameters.Add("@ContentType", SqlDbType.VarChar,50).Value = loFile.PostedFile.ContentType; //记录文件类型
//把其它单表数据记录上传
CmdObj.Parameters.Add("@ImageDescription", SqlDbType.VarChar,200).Value = tbDescription.Text;
//记录文件长度,读取时使用
CmdObj.Parameters.Add("@ImageSize", SqlDbType.BigInt,8).Value = FileLength;
Con.Open();
CmdObj.ExecuteNonQuery();
Con.Close();
//跳转页面
Response.Redirect("ShowAll.aspx");
}
catch
{
}
string strFilePathName = loFile.PostedFile.FileName;
string strFileName = Path.GetFileName(strFilePathName);
int FileLength = loFile.PostedFile.ContentLength;
if(FileLength<=0)
return;
try
{//上传文件
Byte[] FileByteArray = new Byte[FileLength]; //图象文件临时储存Byte数组
Stream StreamObject = loFile.PostedFile.InputStream; //建立数据流对像
//读取图象文件数据,FileByteArray为数据储存体,0为数据指针位置、FileLnegth为数据长度
StreamObject.Read(FileByteArray,0,FileLength);
//建立SQL Server链接
string strCon = System.Configuration.ConfigurationSettings.AppSettings["DSN"];
SqlConnection Con = new SqlConnection(strCon);
String SqlCmd = "INSERT INTO ImageStore (ImageData, ImageContentType, ImageDescription, ImageSize) VALUES (@Image, @ContentType, @ImageDescription, @ImageSize)";
SqlCommand CmdObj = new SqlCommand(SqlCmd, Con);
CmdObj.Parameters.Add("@Image",SqlDbType.Binary, FileLength).Value = FileByteArray;
CmdObj.Parameters.Add("@ContentType", SqlDbType.VarChar,50).Value = loFile.PostedFile.ContentType; //记录文件类型
//把其它单表数据记录上传
CmdObj.Parameters.Add("@ImageDescription", SqlDbType.VarChar,200).Value = tbDescription.Text;
//记录文件长度,读取时使用
CmdObj.Parameters.Add("@ImageSize", SqlDbType.BigInt,8).Value = FileLength;
Con.Open();
CmdObj.ExecuteNonQuery();
Con.Close();
//跳转页面
Response.Redirect("ShowAll.aspx");
}
catch
{
}
取出来显示:
int ImgID = Convert.ToInt32(Request.QueryString["ID"]); //ID为图片ID
//建立数据库链接
string strCon = System.Configuration.ConfigurationSettings.AppSettings["DSN"];
SqlConnection Con = new SqlConnection(strCon);
String SqlCmd = "SELECT * FROM ImageStore WHERE ImageID = @ImageID";
SqlCommand CmdObj = new SqlCommand(SqlCmd, Con);
CmdObj.Parameters.Add("@ImageID", SqlDbType.Int).Value = ImgID;
Con.Open();
SqlDataReader SqlReader = CmdObj.ExecuteReader();
SqlReader.Read();
Response.ContentType = (string)SqlReader["ImageContentType"];//设定输出文件类型
//输出图象文件二进制数制
Response.OutputStream.Write((byte[])SqlReader["ImageData"], 0, (int)SqlReader["ImageSize"]);
Response.End();
//也可以保存为图像
// FileStream fs = new FileStream(@"C:\aa.BMP", FileMode.OpenOrCreate, FileAccess.Write);
// fs.Write((byte[])SqlReader["ImageData"], 0,(int)SqlReader["ImageSize"]);
// fs.Close();
Con.Close();
//建立数据库链接
string strCon = System.Configuration.ConfigurationSettings.AppSettings["DSN"];
SqlConnection Con = new SqlConnection(strCon);
String SqlCmd = "SELECT * FROM ImageStore WHERE ImageID = @ImageID";
SqlCommand CmdObj = new SqlCommand(SqlCmd, Con);
CmdObj.Parameters.Add("@ImageID", SqlDbType.Int).Value = ImgID;
Con.Open();
SqlDataReader SqlReader = CmdObj.ExecuteReader();
SqlReader.Read();
Response.ContentType = (string)SqlReader["ImageContentType"];//设定输出文件类型
//输出图象文件二进制数制
Response.OutputStream.Write((byte[])SqlReader["ImageData"], 0, (int)SqlReader["ImageSize"]);
Response.End();
//也可以保存为图像
// FileStream fs = new FileStream(@"C:\aa.BMP", FileMode.OpenOrCreate, FileAccess.Write);
// fs.Write((byte[])SqlReader["ImageData"], 0,(int)SqlReader["ImageSize"]);
// fs.Close();
Con.Close();
二、文件(图片)保存到硬盘
方法一 /// <summary>
2 /// 下载文件
3 /// </summary>
4 /// <param name="filename">文件物理地址</param>
5 protected void DownloadFile(string filename)
6 {
7
8 string saveFileName = "test.xls";
9 int intStart = filename.LastIndexOf("\\")+1;
10 saveFileName = filename.Substring(intStart,filename.Length-intStart);
11
12 System.IO.FileInfo fi=new System.IO.FileInfo(filename);
13 string fileextname=fi.Extension;
14 string DEFAULT_CONTENT_TYPE = "application/unknown";
15 RegistryKey regkey,fileextkey;
16 string filecontenttype;
17 try
18 {
19 regkey=Registry.ClassesRoot;
20 fileextkey=regkey.OpenSubKey(fileextname);
21 filecontenttype=fileextkey.GetValue("Content Type",DEFAULT_CONTENT_TYPE).ToString();
22 }
23 catch
24 {
25 filecontenttype=DEFAULT_CONTENT_TYPE;
26 }
27
28
29 Response.Clear();
30 Response.Charset = "utf-8";
31 Response.Buffer= true;
32 this.EnableViewState = false;
33 Response.ContentEncoding = System.Text.Encoding.UTF8;
34
35 Response.AppendHeader("Content-Disposition","attachment;filename=" + saveFileName);
36 Response.ContentType=filecontenttype;
37
38 Response.WriteFile(filename);
39 Response.Flush();
40 Response.Close();
41
42 Response.End();
43 }
44
方法二
/// <summary>
2 /// 下载文件
3 /// </summary>
4 /// <param name="filename">文件物理地址</param>
5 protected void DownloadFile(string filename)
6 {
7 string saveFileName = "test.xls";
8 int intStart = filename.LastIndexOf("\\")+1;
9 saveFileName = filename.Substring(intStart,filename.Length-intStart);
10
11 Response.Clear();
12 Response.Charset = "utf-8";
13 Response.Buffer= true;
14 this.EnableViewState = false;
15 Response.ContentEncoding = System.Text.Encoding.UTF8;
16
17 Response.AppendHeader("Content-Disposition","attachment;filename=" + saveFileName);
18 Response.WriteFile(filename);
19 Response.Flush();
20 Response.Close();
21
22 Response.End();
23 }
出现提示框
string strFile="F:\\a.doc";//路径根据实际情况而定
if(!System.IO.File.Exists(strFile))
{
Response.Write("<script language='javascript'>alert('对不起,文件不存在!');</script>");
return;
}
Response.Clear();
Response.ClearHeaders();
Response.Charset = "GB2312";
Response.ContentEncoding =System.Text.Encoding.UTF8;
Response.ContentType = "application/octet-stream";
FileInfo fi=new FileInfo(strFile);
Response.AddHeader("Content-Disposition","attachment; filename=" + HttpUtility.UrlEncode(fi.Name)) ;
Response.AddHeader("Content-Length",fi.Length.ToString());
byte[] tmpbyte=new byte[1024*8];
FileStream fs=fi.OpenRead();
int count;
while((count=fs.Read(tmpbyte,0,tmpbyte.Length))>0)
{
Response.BinaryWrite(tmpbyte);
Response.Flush();
}
fs.Close();
Response.End();
直接在浏览器中打开
string strFile="F:\\a.doc";//路径根据实际情况而定
Response.Clear();
Response.ClearHeaders();
Response.Charset = "GB2312";
Response.ContentEncoding =System.Text.Encoding.UTF8;
Response.ContentType = "application/msword";
Response.WriteFile(strFile);
/// <summary>string strFile="F:\\a.doc";//路径根据实际情况而定
if(!System.IO.File.Exists(strFile))
{
Response.Write("<script language='javascript'>alert('对不起,文件不存在!');</script>");
return;
}
Response.Clear();
Response.ClearHeaders();
Response.Charset = "GB2312";
Response.ContentEncoding =System.Text.Encoding.UTF8;
Response.ContentType = "application/octet-stream";
FileInfo fi=new FileInfo(strFile);
Response.AddHeader("Content-Disposition","attachment; filename=" + HttpUtility.UrlEncode(fi.Name)) ;
Response.AddHeader("Content-Length",fi.Length.ToString());
byte[] tmpbyte=new byte[1024*8];
FileStream fs=fi.OpenRead();
int count;
while((count=fs.Read(tmpbyte,0,tmpbyte.Length))>0)
{
Response.BinaryWrite(tmpbyte);
Response.Flush();
}
fs.Close();
Response.End();
直接在浏览器中打开
string strFile="F:\\a.doc";//路径根据实际情况而定
Response.Clear();
Response.ClearHeaders();
Response.Charset = "GB2312";
Response.ContentEncoding =System.Text.Encoding.UTF8;
Response.ContentType = "application/msword";
Response.WriteFile(strFile);
2 /// 上传图片
3 /// </summary>
4 /// <param name="sender"></param>
5 /// <param name="e"></param>
6 /// <returns>操作结果</returns>
7 private bool ImageUpload(int nWidth,int nHeight)
8 {
9 System.Web.HttpFileCollection files = Request.Files;
10 System.Web.HttpPostedFile pf = files[0];
11 string sOldPath = pf.FileName.ToString();
12 int i = sOldPath.LastIndexOf("\\");
13 string sOldName = sOldPath.Substring(i+1,sOldPath.Length-i-1);
14 //"L"代表大图 && "S"代表缩略图
15 string sTimeNo = System.DateTime.Now.ToString("yyMMddHHmmss");
16 string sNewNameL = "L"+sTimeNo+"_"+sOldName;
17 string sNewNameS = sNewNameL.Replace("L"+sTimeNo,"S"+sTimeNo);
18 string sNewPathL = Server.MapPath("../images/uploadfiles/")+sNewNameL;
19 string sNewPathS = Server.MapPath("../images/uploadfiles/")+sNewNameS;
20 if(System.IO.File.Exists(sNewPathL)||System.IO.File.Exists(sNewPathS))
21 {
22 Page.RegisterStartupScript("FailToUpload","<script>alert('文件名已存在!');</script>");
23 return false;
24 }
25 else
26 {
27 pf.SaveAs(sNewPathL);//保存原图
28 string strContentType = pf.ContentType.ToString();
29 if(strContentType.IndexOf("image/")<0)
30 {
31 Page.RegisterStartupScript("KeyEro","<script>alert('无效的图片格式!');</script>");
32 return false;
33 }
34 else
35 {
36 this.GetThumbNail(sOldPath,strContentType,sNewPathS,nWidth, nHeight);
37 this.Image1.ImageUrl = sNewPathS;
38 return true;
39 }
40 }
41 }
42 /// <summary>
43 /// 生成缩略图
44 /// </summary>
45 /// <param name="FileName">待上传文件的完全限定名</param>
46 /// <param name="strContentType">待上传文件的内容类型</param>
47 /// <param name="path">路径</param>
48 /// <param name="nWidth">宽</param>
49 /// <param name="nHeight">高</param>
50 private void GetThumbNail(string FileName,string strContentType,string path,int nWidth,int nHeight)
51 {
52 System.Drawing.Image oImage;
53 oImage = System.Drawing.Image.FromFile(FileName);
54 oImage = oImage.GetThumbnailImage(nWidth,nHeight,null,IntPtr.Zero);
55 // MemoryStream ms = new MemoryStream();
56 // Response.ContentType = strContentType;
57 // oImage.Save(ms,strContentType);
58 oImage.Save(path,this.GetContenType(strContentType));
59 // ms.WriteTo(Response.OutputStream);
60 }
61 /// <summary>
62 /// 获取保存文件的格式
63 /// </summary>
64 /// <param name="strContentType">待上传文件的内容类型</param>
65 /// <returns>文件格式</returns>
66 private System.Drawing.Imaging.ImageFormat GetContenType(string strContentType)
67 {
68 //只写少数几种格式
69 if(strContentType.ToString().ToLower()== "image/bmp")
70 return System.Drawing.Imaging.ImageFormat.Bmp;
71 else if(strContentType.ToString().ToLower()== "image/gif")
72 return System.Drawing.Imaging.ImageFormat.Gif;
73 else
74 return System.Drawing.Imaging.ImageFormat.Jpeg;
75 }
For example:
Response.ContentType = "image/jpeg";Response.AppendHeader("Content-Disposition","attachment; filename=SailBig.jpg");Response.TransmitFile( Server.MapPath("~/images/sailbig.jpg") );Response.End();
Response.ContentType = "image/jpeg";Response.AppendHeader("Content-Disposition","attachment; filename=SailBig.jpg");Response.TransmitFile( Server.MapPath("~/images/sailbig.jpg") );Response.End();