C# ASP 上传/下载文件
1. 上传文件前台页面
<div style="padding-left:20px;">
<asp:FileUpload ID="FileUpload1" runat="server" style="width:400px;"/>
<asp:Button ID="Button1" runat="server" OnClick="Upload_Click" Text="上传" style="width:65px;height:22px"></asp:Button >
</div>
上传文件后台代码
private string _directory = @"../Questionnaire35"; protected void Upload_Click(object sender, EventArgs e)
{
try
{
if (Request.Files.Count > )
{
if (string.IsNullOrEmpty(Request.Files[].FileName))
{
return;
}
//判断文件大小
int length = Request.Files[].ContentLength;
if (length > )
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "<script>alert('文件大于1M,不能上传');</script>");
return;
} string type = Request.Files[].ContentType;
string fileExt = Path.GetExtension(Request.Files[].FileName).ToLower();
//只能上传图片,过滤不可上传的文件类型
string fileFilt = ".xlsx|.xls|.docx|.doc|......";
if (fileFilt.IndexOf(fileExt) <= -)
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "<script>alert('只能上传文档');</script>");
return;
}
else
{
UserInfo user = (UserInfo)Session["UserInfo"];
//string fileName = Server.MapPath(_directory) + "\\" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + fileExt;
string fileName = Server.MapPath(_directory) + "\\" + user.Pkid + fileExt;
Request.Files[].SaveAs(fileName);
Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "<script>alert('上传成功');</script>");
Answer answer = (Answer)Session["Answer"];
answer.Answer35 = "done";
}
}
}
catch
{
throw new Exception();
}
}
需要引入 using System.IO;
2. 下载文件前台页面
<asp:LinkButton runat="server" ID="DownLoadQuestionnaire" Text="下载文件" OnClick="DownLoadQuestionnaire_Click" />
下载文件后台代码
protected void DownLoadQuestionnaire_Click(object sender, EventArgs e)
{
Response.ContentType = "application/x-zip-compressed"; string docName = "中高职衔接院校调研问卷.docx"; //文件路径
docName = HttpUtility.UrlEncode(docName, System.Text.Encoding.UTF8);
Response.AddHeader("Content-Disposition", "attachment;filename=" + docName);
string filename = Server.MapPath("DownLoad/中高职衔接院校调研问卷.docx");
//指定编码 防止中文文件名乱码
Response.HeaderEncoding = System.Text.Encoding.GetEncoding("GB2312");
Response.TransmitFile(filename); }
值得注意的就是文件名设置一下编码,不然出现下载时文件名乱码:
HttpUtility.UrlEncode(docName, System.Text.Encoding.UTF8);
据说还有很多种下载方式,没一个一个的试验:
protected void DownLoadQuestionnaire_Click(object sender, EventArgs e)
{
string fileName = "asd.txt";//客户端保存的文件名
string filePath = Server.MapPath("DownLoad/aaa.txt");//路径 FileInfo fileInfo = new FileInfo(filePath);
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.AddHeader("Content-Disposition", "attachment;filename=" + 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(); } protected void DownLoadQuestionnaire_Click(object sender, EventArgs e)
{
string fileName = "aaa.txt";//客户端保存的文件名
string filePath = Server.MapPath("DownLoad/aaa.txt");//路径
System.IO.FileInfo fileInfo = new System.IO.FileInfo(filePath);
if (fileInfo.Exists == true)
{
const long ChunkSize = ;//100K 每次读取文件,只读取100K,这样可以缓解服务器的压力
byte[] buffer = new byte[ChunkSize]; Response.Clear();
System.IO.FileStream iStream = System.IO.File.OpenRead(filePath);
long dataLengthToRead = iStream.Length;//获取下载的文件总大小
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName));
while (dataLengthToRead > && Response.IsClientConnected)
{
int lengthRead = iStream.Read(buffer, , Convert.ToInt32(ChunkSize));//读取的大小
Response.OutputStream.Write(buffer, , lengthRead);
Response.Flush();
dataLengthToRead = dataLengthToRead - lengthRead;
}
Response.Close();
}
} protected void DownLoadQuestionnaire_Click(object sender, EventArgs e)
{
string fileName = "aaa.txt";//客户端保存的文件名
string filePath = Server.MapPath("DownLoad/aaa.txt");//路径 //以字符流的形式下载文件
FileStream fs = new FileStream(filePath, FileMode.Open);
byte[] bytes = new byte[(int)fs.Length];
fs.Read(bytes, , bytes.Length);
fs.Close();
Response.ContentType = "application/octet-stream";
//通知浏览器下载文件而不是打开
Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
}
C# ASP 上传/下载文件的更多相关文章
- rz和sz上传下载文件工具lrzsz
######################### rz和sz上传下载文件工具lrzsz ####################################################### ...
- linux上很方便的上传下载文件工具rz和sz
linux上很方便的上传下载文件工具rz和sz(本文适合linux入门的朋友) ##########################################################&l ...
- shell通过ftp实现上传/下载文件
直接代码,shell文件名为testFtptool.sh: #!/bin/bash ########################################################## ...
- SFTP远程连接服务器上传下载文件-qt4.8.0-vs2010编译器-项目实例
本项目仅测试远程连接服务器,支持上传,下载文件,更多功能开发请看API自行开发. 环境:win7系统,Qt4.8.0版本,vs2010编译器 qt4.8.0-vs2010编译器项目实例下载地址:CSD ...
- linux下常用FTP命令 上传下载文件【转】
1. 连接ftp服务器 格式:ftp [hostname| ip-address]a)在linux命令行下输入: ftp 192.168.1.1 b)服务器询问你用户名和密码,分别输入用户名和相应密码 ...
- C#实现http协议支持上传下载文件的GET、POST请求
C#实现http协议支持上传下载文件的GET.POST请求using System; using System.Collections.Generic; using System.Text; usin ...
- HttpClient上传下载文件
HttpClient上传下载文件 java HttpClient Maven依赖 <dependency> <groupId>org.apache.httpcomponents ...
- 初级版python登录验证,上传下载文件加MD5文件校验
服务器端程序 import socket import json import struct import hashlib import os def md5_code(usr, pwd): ret ...
- 如何利用京东云的对象存储(OSS)上传下载文件
作者:刘冀 在公有云厂商里都有对象存储,京东云也不例外,而且也兼容S3的标准因此可以利用相关的工具去上传下载文件,本文主要记录一下利用CloudBerry Explorer for Amazon S3 ...
随机推荐
- bzoj1528[POI2005]sam-Toy Cars*&&bzoj1826[JSOI2010]缓存交换
bzoj1528[POI2005]sam-Toy Cars bzoj1826[JSOI2010]缓存交换 题意: Jasio有n个不同的玩具,它们都被放在了很高的架子上,地板上不会有超过k个玩具.当J ...
- 【学习记录】C#保存数据至CSV文档 & DateTime格式模式控制解释
数据类的定义: public class Result_Display { private string id; public string ID { get { return id; } set { ...
- Cyber Security - Palo Alto Firewall Interface Types
Multiple options to integrate the Palo Alto Firewall into your: Network Layer 2 interfaces and VLAN ...
- Oracle数据库服务器更改计算机名称,导致监听服务打不开解决办法
1.修改listener.ora和tnsnames.ora文件 文件路径为:C:\Oracle\Instanclient_11_2\network\admin # listener.ora Netwo ...
- 浅谈6种JS数组遍历方法的区别
本篇文章给大家介绍一下6种JS数组遍历方法:for.foreach.for in.for of.. each. ().each的区别.有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助. ...
- 雪碧图——CSS Sprites(精灵)
在日常开发打开文件包,打开static文件夹,有一张图片,里面融合了这个应用都会用到的小图标,其实,主要是减少应用渲染出现繁多的请求,加速页面渲染. 解决方案:使用css背景定位 icon {widt ...
- python xpath的基本用法
XPath是一种在XML文档中查找信息的语言,使用路径表达式在XML文档中进行导航.学习XPath需要对XML和HTML有基本的了解. 在XPath中,有七种类型的节点:文档(根)节点.元素.属性.文 ...
- ✨Shell脚本实现Base64 加密解密
加密算法 # !/bin/bash # 全局变量 str="" base64_encode_string(){ # 源数据 source_string=$1 echo " ...
- PHP atan() 函数
实例 通过 atan() 函数返回不同数的反正切: <?phpecho(atan(0.50) . "<br>");echo(atan(-0.50) . " ...
- PHP quoted_printable_decode() 函数
实例 对经过 quoted-printable 编码后的字符串进行解码,返回 8 位的 ASCII 字符串: <?php高佣联盟 www.cgewang.com$str = "Hell ...