fileupload控件上传、文件下载
常遇到上传下载的功能,这里把我习惯的用法写下来:
上传:
string fileName = "";
fileName = this.fu_pic.FileName;
if (string.IsNullOrEmpty(fileName))
isPic = "0";
else
isPic = "1";
//附件不为空的时候上传图片,否则不处理
if (isPic == "1")
{
byte[] arrayByte = this.fu_pic.FileBytes;
if (arrayByte.Length <= 0)
{
//Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('上传图片是空文件!')</script>");
AlertMessage("上传图片是空文件!");
this.fu_pic.Focus();
return;
}
string extention = fileName.Substring(fileName.LastIndexOf(".") + 1);
if (extention.ToUpper() != "JPG"
&& extention.ToUpper() != "BMP"
&& extention.ToUpper() != "PNG"
&& extention.ToUpper() != "GIF")
{
//Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('图片格式错误,请上传jpg/bmp/png/gif格式图片!')</script>");
AlertMessage(@"图片格式错误,请上传jpg/bmp/png/gif格式图片!");
this.fu_pic.Focus();
return;
}
else
{
//按照年/月 生成文件目录
fileName = string.Format(@"UploadImage\{0}\{3}\{1}{2}", DateTime.Now.Year.ToString(), DateTime.Now.ToString("yyyyMMddHHmmssfff"), fileName, DateTime.Now.Month.ToString());
//获取附件上传物理路径(这里设置在config文件中)
string dePath = ConfigurationManager.AppSettings["upload"].ToString();
string filePath = Path.Combine(dePath, fileName);//Server.MapPath(@".." + fileName);//外面一层就是网站目录
if (saveView(arrayByte, filePath))
{
//saveAttach = true;
}
else
{
//saveAttach = false;
//Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('图片上传服务器失败!')</script>");
AlertMessage("图片上传服务器失败!");
this.fu_pic.Focus();
return;
}
}
}
public bool saveView(byte[] arry_byte, string filePath)
{
bool rst = false;
FileStream saveStream = null;
try
{
//判断文件夹是否存在
FileInfo file = new FileInfo(filePath);
if (!file.Exists)
{
if (!Directory.Exists(file.DirectoryName))
Directory.CreateDirectory(file.DirectoryName);
}
file = null;
//保存文件
saveStream = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
saveStream.Write(arry_byte, 0, arry_byte.Length);
saveStream.Close();
rst = true;
}
catch (Exception)
{
rst = false;
}
return rst;
}
下载保存:
/// <summary>
/// 下载服务端文件
/// </summary>
/// <param name="fileName">下载时客户端显示名称</param>
/// <param name="filePath">服务端文件完全物理路径</param>
/// <returns></returns>
public void DownloadFile(string fileName, string filePath)
{
//服务端文件是否存在
if (File.Exists(filePath))
{
FileInfo fi = new FileInfo(filePath);
long length = fi.Length;
//读取文件到流sr中,using为防止文件被进程占据,强制释放资源
using (FileStream sr = new FileStream(filePath, FileMode.Open))
{
int startlength = 0;
int bufferSize = 1;
byte[] buffer = new byte[bufferSize];
byte[] allBuffer = new byte[length];
//循环读取流到allBuffer中
while (startlength < length)
{
//读取bytes个字节到buff中的0到bufferSize位置
//sr.read后,sr自动移动到读取的位置
int bytes = sr.Read(buffer, 0, bufferSize);
//将buff内容存入allBuffer中
allBuffer[startlength] = buffer[0];
//前进bytes个位置
startlength += bytes;
}
//清空缓存中的流
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
//输出流
Response.AddHeader("Accept-Ranges", "bytes");
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName, Encoding.GetEncoding("gb2312")));
Response.BinaryWrite(allBuffer);
Response.Flush();
Response.End();
}
}
}
更加简洁的下载:
string fileName = "日志.txt";
string txtFullFilePath = "c:/test/aa.txt";
if (File.Exists(Server.MapPath(txtFullFilePath)))
{
//文件对象
FileInfo fileInfo = new FileInfo(Server.MapPath(txtFullFilePath));
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName));
Response.AddHeader("Content-Length", fileInfo.Length.ToString());
Response.AddHeader("Content-Transfer-Encoding", "binary");
Response.ContentType = "application/octet-stream";
Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
Response.WriteFile(fileInfo.FullName);
Response.Flush();
Response.End();
}
fileupload控件上传、文件下载的更多相关文章
- .net简单的fileupload控件上传
前台代码: <asp:FileUpload ID="FileUpload1" runat="server" /> <asp:Button ID ...
- WebForm使用FileUpload控件上传压缩二进制图片
fuImage 是FileUpload页面控件 ImageHelper.CompressionImage(fuImage.FileBytes, quality); /// <summary> ...
- asp.net FileUpload 控件上传文件 以二进制的形式存入数据库并将图片显示出来
图片上传事件代码如下所示: byte[] binary = upload.FileBytes; StringBuilder sqlStrSb = new StringBuilder(); sqlStr ...
- asp:FileUpload 控件上传多文件
<asp:FileUpload runat="server" ID="imgUpload" AllowMultiple="true" ...
- FileUpload的控件上传excel
在一个使用FileUpload的控件上传excel,读取excel的数据 因为上传的路径一直被限定在C:\Program\IIS\Express 一直限制这个文件下, 想要解决这个问题. 在谷歌浏览器 ...
- MVC项目使用easyui的filebox控件上传文件
开发环境:WIN10+IE11,浏览器请使用IE10或以上版本 开发技术框架MVC4+JQuery Easyui+knockoutjs 效果为弹出小窗体,如下图 1.前端cshtml文件代码(只包含文 ...
- JS ajaxfileUpload 一次性上传多个input控件 上传多个文件
本方法适用于一次性上传多个input框输入的文件,如下图所示,任务是需要一次上传两个input框提供的两个文件. 具体方法: 1.修改ajax调用方法 如上图所示,只需要将ajaxFileUpload ...
- c#上传文件(一)使用 .net 控件上传文件
1.html代码: <body> <form id="form1" runat="server"> <div> <as ...
- upload控件上传json文件合并的两种方法
方法一: byte[] byte1 = FileUpload1.FileBytes; byte[] byte2 = FileUpload2.FileBytes; byte[] a1 = Encodin ...
随机推荐
- CQRS学习——IOC,配置,仓储隔离以及QueryEntry[其三]
从IoC开始说起 博主最早开始用的IoC容器叫AutoFac,那时候用它主要是为了生命周期管理——将EF上下文的生命周期限定为每请求.当然也总是每每听到IoC的好处,但是仍然不能理解其优势.最近在学习 ...
- Linux的直接I/O机制
转自Linux的直接I/O机制 对于传统的操作系统来说,普通的 I/O 操作一般会被内核缓存,这种 I/O 被称作缓存 I/O.本文所介绍的文件访问机制不经过操作系统内核的缓存,数据直接在磁盘和应用程 ...
- Python图形图像处理库的介绍之Image模块
http://onlypython.group.iteye.com/group/wiki/1372-python-graphics-image-processing-library-introduce ...
- 李洪强iOS开发之-PCH文件的配置
pch 可以用来存储共享信息,比如设备屏幕的宽度,高度.版本号等等 公用信息 Xcode 老版本会自动为我们创建pch文件,新版本开始不自动创建了,如果需要使用可以自己手动创建 创建完成后可以在里面定 ...
- Java程序发展之路
- QT使用UAC(经过验证)
网上有很多manifest的版本,mingw与vs系列也有不同的解决方案,不管那么多,我是使用这篇文章解决这个问题的: So it turns out that I had another bug t ...
- 中文乱码的分析 和 从Eclipse设置启动JVM时的字符集(转)
最近时常碰到中文乱码的问题,eclipse的编码环境设置的都是UTF-8,外部也是以UTF-8的编码进行传参的,但是遇到中文的时候还是因为乱码而产生一系列的错误.在网上查了许多资料,发现这是跟JVM的 ...
- Ember.js demo2
<!DOCTYPE html> <html> <head> <script src="http://code.jquery.com/jquery-1 ...
- [译]GotW #6b Const-Correctness, Part 2
const和mutable对于书写安全代码来说是个很有利的工具,坚持使用它们. Problem Guru Question 在下面代码中,在只要合适的情况下,对const进行增加和删除(包括 ...
- 【POJ】3076 Sudoku
DLX第一题,模板留念. /* 3076 */ #include <iostream> #include <string> #include <map> #incl ...