文件(图片生产缩略图)的上传与下载

简介:

一、文件(图片)保存到数据库
None.gif // 得到用户要上传的文件名
None.gif
             string  strFilePathName  =  loFile.PostedFile.FileName;
None.gif            
string  strFileName  =  Path.GetFileName(strFilePathName);
None.gif            
int  FileLength  =  loFile.PostedFile.ContentLength;
None.gif            
if (FileLength <= 0 )
None.gif                
return ;
None.gif            
try
ExpandedBlockStart.gif            
{//上传文件
InBlock.gif
                Byte[] FileByteArray = new Byte[FileLength]; //图象文件临时储存Byte数组
InBlock.gif
                Stream StreamObject = loFile.PostedFile.InputStream; //建立数据流对像
InBlock.gif                
//读取图象文件数据,FileByteArray为数据储存体,0为数据指针位置、FileLnegth为数据长度
InBlock.gif
                StreamObject.Read(FileByteArray,0,FileLength); 
InBlock.gif                
//建立SQL Server链接
InBlock.gif
                string strCon = System.Configuration.ConfigurationSettings.AppSettings["DSN"];
InBlock.gif                SqlConnection Con 
= new SqlConnection(strCon);
InBlock.gif                String SqlCmd 
= "INSERT INTO ImageStore (ImageData, ImageContentType, ImageDescription, ImageSize) VALUES (@Image, @ContentType, @ImageDescription, @ImageSize)";
InBlock.gif                SqlCommand CmdObj 
= new SqlCommand(SqlCmd, Con);
InBlock.gif                CmdObj.Parameters.Add(
"@Image",SqlDbType.Binary, FileLength).Value = FileByteArray;
InBlock.gif                CmdObj.Parameters.Add(
"@ContentType", SqlDbType.VarChar,50).Value = loFile.PostedFile.ContentType; //记录文件类型
InBlock.gif                
//把其它单表数据记录上传
InBlock.gif
                CmdObj.Parameters.Add("@ImageDescription", SqlDbType.VarChar,200).Value = tbDescription.Text;
InBlock.gif                
//记录文件长度,读取时使用
InBlock.gif
                CmdObj.Parameters.Add("@ImageSize", SqlDbType.BigInt,8).Value = FileLength;
InBlock.gif                Con.Open();
InBlock.gif                CmdObj.ExecuteNonQuery(); 
InBlock.gif                Con.Close();
InBlock.gif                
//跳转页面
InBlock.gif
                Response.Redirect("ShowAll.aspx");
ExpandedBlockEnd.gif            }

None.gif            
catch
ExpandedBlockStart.gif            
{
ExpandedBlockEnd.gif            }

取出来显示:
None.gif int  ImgID  =  Convert.ToInt32(Request.QueryString[ " ID " ]);  // ID为图片ID 
None.gif            
// 建立数据库链接
None.gif
             string  strCon  =  System.Configuration.ConfigurationSettings.AppSettings[ " DSN " ];
None.gif            SqlConnection Con 
=   new  SqlConnection(strCon);
None.gif            String SqlCmd 
=   " SELECT * FROM ImageStore WHERE ImageID = @ImageID " ;
None.gif            SqlCommand CmdObj 
=   new  SqlCommand(SqlCmd, Con);
None.gif            CmdObj.Parameters.Add(
" @ImageID " , SqlDbType.Int).Value  =  ImgID;
None.gif            Con.Open();
None.gif            SqlDataReader SqlReader 
=  CmdObj.ExecuteReader();
None.gif            SqlReader.Read(); 
None.gif            Response.ContentType 
=  ( string )SqlReader[ " ImageContentType " ]; // 设定输出文件类型
None.gif            
// 输出图象文件二进制数制
None.gif
            Response.OutputStream.Write(( byte [])SqlReader[ " ImageData " ],  0 , ( int )SqlReader[ " ImageSize " ]); 
None.gif            Response.End();
None.gif            
// 也可以保存为图像
None.gif
//             FileStream fs = new FileStream(@"C:\aa.BMP", FileMode.OpenOrCreate, FileAccess.Write);
None.gif
//             fs.Write((byte[])SqlReader["ImageData"], 0,(int)SqlReader["ImageSize"]);
None.gif
//             fs.Close();
None.gif

None.gif            Con.Close();

二、文件(图片)保存到硬盘   
方法一   /// <summary>
 2InBlock.gif        /// 下载文件
 3InBlock.gif        /// </summary>
 4ExpandedBlockEnd.gif        /// <param name="filename">文件物理地址</param>

 5 None.gif          protected   void  DownloadFile( string  filename)
 6 ExpandedBlockStart.gif         {
 7InBlock.gif
 8InBlock.gif            string saveFileName = "test.xls";
 9InBlock.gif            int intStart = filename.LastIndexOf("\\")+1;
10InBlock.gif            saveFileName = filename.Substring(intStart,filename.Length-intStart);
11InBlock.gif
12InBlock.gif            System.IO.FileInfo fi=new System.IO.FileInfo(filename);
13InBlock.gif            string fileextname=fi.Extension;
14InBlock.gif            string DEFAULT_CONTENT_TYPE = "application/unknown";
15InBlock.gif            RegistryKey regkey,fileextkey;
16InBlock.gif            string filecontenttype;
17InBlock.gif            try 
18ExpandedSubBlockStart.gif            {                
19InBlock.gif                regkey=Registry.ClassesRoot;                
20InBlock.gif                fileextkey=regkey.OpenSubKey(fileextname);                
21InBlock.gif                filecontenttype=fileextkey.GetValue("Content Type",DEFAULT_CONTENT_TYPE).ToString();
22ExpandedSubBlockEnd.gif            }

23InBlock.gif            catch
24ExpandedSubBlockStart.gif            {
25InBlock.gif                filecontenttype=DEFAULT_CONTENT_TYPE;
26ExpandedSubBlockEnd.gif            }
      
27InBlock.gif
28InBlock.gif
29InBlock.gif            Response.Clear();
30InBlock.gif            Response.Charset = "utf-8";
31InBlock.gif            Response.Buffer= true;
32InBlock.gif            this.EnableViewState = false;
33InBlock.gif            Response.ContentEncoding = System.Text.Encoding.UTF8;
34InBlock.gif
35InBlock.gif            Response.AppendHeader("Content-Disposition","attachment;filename=" + saveFileName); 
36InBlock.gif            Response.ContentType=filecontenttype;
37InBlock.gif
38InBlock.gif            Response.WriteFile(filename); 
39InBlock.gif            Response.Flush();
40InBlock.gif            Response.Close();
41InBlock.gif
42InBlock.gif            Response.End();
43ExpandedBlockEnd.gif        }

44 None.gif     
方法二
  /// <summary>
 2InBlock.gif        /// 下载文件
 3InBlock.gif        /// </summary>
 4ExpandedBlockEnd.gif        /// <param name="filename">文件物理地址</param>

 5None.gif        protected void DownloadFile(string filename)
 6ExpandedBlockStart.gif        {
 7InBlock.gif            string saveFileName = "test.xls";
 8InBlock.gif            int intStart = filename.LastIndexOf("\\")+1;
 9InBlock.gif            saveFileName = filename.Substring(intStart,filename.Length-intStart);
10InBlock.gif
11InBlock.gif            Response.Clear();
12InBlock.gif            Response.Charset = "utf-8";
13InBlock.gif            Response.Buffer= true;
14InBlock.gif            this.EnableViewState = false;
15InBlock.gif            Response.ContentEncoding = System.Text.Encoding.UTF8;
16InBlock.gif
17InBlock.gif            Response.AppendHeader("Content-Disposition","attachment;filename=" + saveFileName); 
18InBlock.gif            Response.WriteFile(filename); 
19InBlock.gif            Response.Flush();
20InBlock.gif            Response.Close();
21InBlock.gif
22InBlock.gif            Response.End();
23ExpandedBlockEnd.gif        }文件的ContentType类型 小全
ContractedBlock.gif dot.gif
None.gif 出现提示框
None.gif
None.gif
string  strFile = " F:\\a.doc " ; // 路径根据实际情况而定
None.gif
if ( ! System.IO.File.Exists(strFile))
ExpandedBlockStart.gif   
{
InBlock.gif    Response.Write(
"<script language='javascript'>alert('对不起,文件不存在!');</script>");
InBlock.gif    
return;
ExpandedBlockEnd.gif   }

None.gif   Response.Clear();
None.gif   Response.ClearHeaders();
None.gif   Response.Charset 
=   " GB2312 " ;
None.gif   Response.ContentEncoding 
= System.Text.Encoding.UTF8;
None.gif   Response.ContentType 
=   " application/octet-stream "
None.gif   FileInfo fi
= new  FileInfo(strFile);
None.gif   Response.AddHeader(
" Content-Disposition " , " attachment;  filename= "    +   HttpUtility.UrlEncode(fi.Name)) ;
None.gif   Response.AddHeader(
" Content-Length " ,fi.Length.ToString());
None.gif   
byte [] tmpbyte = new   byte [ 1024 * 8 ];
None.gif   FileStream fs
= fi.OpenRead();
None.gif   
int  count;
None.gif   
while ((count = fs.Read(tmpbyte, 0 ,tmpbyte.Length)) > 0 )
ExpandedBlockStart.gif   
{
InBlock.gif    Response.BinaryWrite(tmpbyte);
InBlock.gif    Response.Flush();
ExpandedBlockEnd.gif   }

None.gif   fs.Close();   
None.gif   Response.End();
None.gif
None.gif直接在浏览器中打开
None.gif   
string  strFile = " F:\\a.doc " ; // 路径根据实际情况而定
None.gif
   Response.Clear();
None.gif   Response.ClearHeaders();
None.gif   Response.Charset 
=   " GB2312 " ;
None.gif   Response.ContentEncoding 
= System.Text.Encoding.UTF8;
None.gif   Response.ContentType 
=   " application/msword "
None.gif   Response.WriteFile(strFile);
None.gif
None.gif
/// <summary>
 2InBlock.gif        /// 上传图片
 3InBlock.gif        /// </summary>
 4InBlock.gif        /// <param name="sender"></param>  
 5InBlock.gif        /// <param name="e"></param>
 6ExpandedBlockEnd.gif        /// <returns>操作结果</returns>

 7 None.gif          private   bool  ImageUpload( int  nWidth, int  nHeight)
 8 ExpandedBlockStart.gif         {
 9InBlock.gif            System.Web.HttpFileCollection files = Request.Files;
10InBlock.gif            System.Web.HttpPostedFile pf = files[0];
11InBlock.gif            string sOldPath = pf.FileName.ToString();
12InBlock.gif            int i = sOldPath.LastIndexOf("\\");
13InBlock.gif            string sOldName = sOldPath.Substring(i+1,sOldPath.Length-i-1);
14InBlock.gif            //"L"代表大图 && "S"代表缩略图
15InBlock.gif            string sTimeNo = System.DateTime.Now.ToString("yyMMddHHmmss");
16InBlock.gif            string sNewNameL = "L"+sTimeNo+"_"+sOldName;
17InBlock.gif            string sNewNameS = sNewNameL.Replace("L"+sTimeNo,"S"+sTimeNo);
18InBlock.gif            string sNewPathL = Server.MapPath("../images/uploadfiles/")+sNewNameL;
19InBlock.gif            string sNewPathS = Server.MapPath("../images/uploadfiles/")+sNewNameS;
20InBlock.gif            if(System.IO.File.Exists(sNewPathL)||System.IO.File.Exists(sNewPathS))
21ExpandedSubBlockStart.gif            {
22InBlock.gif                Page.RegisterStartupScript("FailToUpload","<script>alert('文件名已存在!');</script>");
23InBlock.gif                return false;
24ExpandedSubBlockEnd.gif            }

25InBlock.gif            else
26ExpandedSubBlockStart.gif            {
27InBlock.gif                pf.SaveAs(sNewPathL);//保存原图
28InBlock.gif                string strContentType = pf.ContentType.ToString();
29InBlock.gif                if(strContentType.IndexOf("image/")<0)
30ExpandedSubBlockStart.gif                {
31InBlock.gif                    Page.RegisterStartupScript("KeyEro","<script>alert('无效的图片格式!');</script>");
32InBlock.gif                    return false;
33ExpandedSubBlockEnd.gif                }

34InBlock.gif                else
35ExpandedSubBlockStart.gif                {
36InBlock.gif                    this.GetThumbNail(sOldPath,strContentType,sNewPathS,nWidth, nHeight);
37InBlock.gif                    this.Image1.ImageUrl = sNewPathS;
38InBlock.gif                    return true;
39ExpandedSubBlockEnd.gif                }

40ExpandedSubBlockEnd.gif            }

41ExpandedBlockEnd.gif        }

42 ExpandedBlockStart.gif         /// <summary>
43InBlock.gif        /// 生成缩略图
44InBlock.gif        /// </summary>
45InBlock.gif        /// <param name="FileName">待上传文件的完全限定名</param>
46InBlock.gif        /// <param name="strContentType">待上传文件的内容类型</param>
47InBlock.gif        /// <param name="path">路径</param>
48InBlock.gif        /// <param name="nWidth"></param>
49ExpandedBlockEnd.gif        /// <param name="nHeight"></param>

50 None.gif          private   void  GetThumbNail( string  FileName, string  strContentType, string  path, int  nWidth, int  nHeight)
51 ExpandedBlockStart.gif         {
52InBlock.gif            System.Drawing.Image oImage;
53InBlock.gif            oImage = System.Drawing.Image.FromFile(FileName);
54InBlock.gif            oImage = oImage.GetThumbnailImage(nWidth,nHeight,null,IntPtr.Zero);
55InBlock.gif            //            MemoryStream ms = new MemoryStream();
56InBlock.gif            //            Response.ContentType = strContentType;
57InBlock.gif            //            oImage.Save(ms,strContentType);
58InBlock.gif            oImage.Save(path,this.GetContenType(strContentType));
59InBlock.gif            //            ms.WriteTo(Response.OutputStream);
60ExpandedBlockEnd.gif        }

61 ExpandedBlockStart.gif         /// <summary>
62InBlock.gif        /// 获取保存文件的格式
63InBlock.gif        /// </summary>
64InBlock.gif        /// <param name="strContentType">待上传文件的内容类型</param>
65ExpandedBlockEnd.gif        /// <returns>文件格式</returns>

66 None.gif          private  System.Drawing.Imaging.ImageFormat GetContenType( string  strContentType)
67 ExpandedBlockStart.gif         {
68InBlock.gif            //只写少数几种格式
69InBlock.gif            if(strContentType.ToString().ToLower()== "image/bmp")
70InBlock.gif                return System.Drawing.Imaging.ImageFormat.Bmp;
71InBlock.gif            else if(strContentType.ToString().ToLower()== "image/gif")
72InBlock.gif                return System.Drawing.Imaging.ImageFormat.Gif;
73InBlock.gif            else
74InBlock.gif            return System.Drawing.Imaging.ImageFormat.Jpeg;
75ExpandedBlockEnd.gif        }

None.gif For example:
None.gif
None.gifResponse.ContentType 
=   " image/jpeg " ;Response.AppendHeader( " Content-Disposition " , " attachment; filename=SailBig.jpg " );Response.TransmitFile( Server.MapPath( " ~/images/sailbig.jpg " ) );Response.End();



本文转自高海东博客园博客,原文链接:http://www.cnblogs.com/ghd258/archive/2005/10/17/256596.html,如需转载请自行联系原作者
相关文章
|
15天前
|
API
【sgUpload】自定义组件:自定义上传组件,支持上传文件夹及其子文件夹文件、批量上传,批量上传会有右下角上传托盘出现,支持本地上传图片转换为Base64image。
【sgUpload】自定义组件:自定义上传组件,支持上传文件夹及其子文件夹文件、批量上传,批量上传会有右下角上传托盘出现,支持本地上传图片转换为Base64image。
|
8月前
针对FastAdmin新增上传多个图片,新增上传的视频的预览效果
针对FastAdmin新增上传多个图片,新增上传的视频的预览效果
373 0
|
6月前
|
存储 小程序 JavaScript
小程序云开发上传及使用图片
小程序云开发上传及使用图片
93 0
|
数据采集 JavaScript 开发者
批量下载一些图片
学习的最大理由是想摆脱平庸,早一天就多一份人生的精彩;迟一天就多一天平庸的困扰。各位小伙伴,如果您:
176 0
|
JavaScript
原生js实现图片单张上传及批量上传
原生js实现图片单张上传及批量上传
|
JavaScript 程序员 API
Nodejs实现图片的上传、压缩预览、定时删除。
我们程序员日常都会用到图片压缩,面对这么常用的功能,肯定要尝试实现一番。
|
存储 Web App开发 前端开发
移动端图片操作(一)——上传
上传我们一般都是用“input[type=file]”控件。当你用此控件时,你就授权了网页和服务器访问对应的文件,就可以得到File对象。
移动端图片操作(一)——上传
|
数据采集 Web App开发 Java
实现网络图片爬虫,只需5秒快速把整个网页上的图片全下载打包zip
我们经常需要用到互联网上的一些共享资源,图片就是资源的一种,怎么把网页上的图片批量下载下来?有时候我们需要把网页上的图片下载下来,但网页上图片那么多,怎么下载我们想要的东西呢,如果这个网页都是我们想要的图片,难道我们要一点一点一张一张右键下载吗? 当然不好,这里提供一段Java实现的网络爬虫抓图片代码,程序员同志有喜欢的记得收藏哦, 材料:必须会java开发,用到的核心jar Jsoup自己去网上下载很多。
1108 0

热门文章

最新文章