博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
文件(图片生产缩略图)的上传与下载
阅读量:6136 次
发布时间:2019-06-21

本文共 8139 字,大约阅读时间需要 27 分钟。

一、文件(图片)保存到数据库
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,如需转载请自行联系原作者
你可能感兴趣的文章
canvas学习总结
查看>>
Javascript的if判断
查看>>
spring cloud gateway 源码解析(3)记录请求参数及返回的json
查看>>
阿里云ECS数据盘格式化与挂载图文教程
查看>>
Flexbox响应式网页布局 - W3Schools视频02
查看>>
【手牵手】搭建前端组件库(二)
查看>>
怎么给视频添加音频或配乐
查看>>
怎么转换音乐格式
查看>>
Leaflet-Develop-Guide
查看>>
每隔1s打印0-5
查看>>
Angular6错误 Service: No provider for Renderer2
查看>>
聊聊flink的BlobStoreService
查看>>
洗牌算法具体指的是什么?
查看>>
HBuilder打包手机app的方法
查看>>
解决Mac下SSH闲时自动中断的问题
查看>>
在JavaScript中理解策略模式
查看>>
ArchSummit 深圳 2017 成功举办,探索未来互联网架构
查看>>
不知道如何提升深度学习性能?我们为你整理了这份速查清单
查看>>
Go 2提上日程,官方团队呼吁社区给新特性提案提交反馈
查看>>
技术绩效考量:你们可能都做错了
查看>>