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 ...
随机推荐
- OSCP Learning Notes - Capstone(3)
DroopyCTF Walkthrough Preparation: Download the DroopyCTF virtual machine from the following website ...
- 【bfs+链式向前星】防御僵尸(defend)计蒜客 - 45288
题目: A 国有 n 座城市,n−1 条双向道路将这些城市连接了起来,任何两个城市都可以通过道路互通. 某日,A 国爆发了丧尸危机,所有的幸存者现在都聚集到了 A 国的首都(首都是编号为 1 的城市) ...
- ELK5.6.4+Redis+Filebeat+Nginx(CentOS7.4)
下载地址: Elasticsearhc: https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-5.6.4.tar.gz ...
- Oracle数据库出现[23000][2291] ORA-02291: integrity constraint (SIMTH.SYS_C005306) violated异常
参考链接 这个异常发生在往中间表中插入数据时,这时出现异常是因为关联的某个表没有插入数据,所以给没有插入数据的关联表插入数据,再给中间表插入数据此时异常就会解决.
- MapReduce之Combiner合并
Combiner是MR程序中Mapper和Reducer之外的一种组件(本质是一个Reducer类) Combinr组件的父类就是Reducer Conbimer只有在驱动类里设置了之后,才会运行 C ...
- Dynamics365 Field Service Work Order Theory
Come from :https://neilparkhurst.com/2016/08/20/field-service-work-order-theory/ In this post I aim ...
- linux条件测试操作(test)和if判断语句,while循环语句,break控制语句和for循环和case多分枝语句和select语句
条件测试操作 条件测试是专为影响"$?"的操作,是条件转移.循环语句的基础 test测试命令: test 用途:测试特定的表达式是否成立,当条件成立时,命令执行后的返回值为0, ...
- Pandas 数据处理 | Datetime 在 Pandas 中的一些用法!
Datatime 是 Python 中一种时间数据类型,对于不同时间格式之间的转换是比较方便的,而在 Pandas 中也同样支持 DataTime 数据机制,可以借助它实现许多有用的功能,例如 1,函 ...
- 题解 Luogu P1514 【引水入城】
有一种神奇的算法叫做floodfill 就是一个n*m的矩阵,a[i][j]为当前高度,我们可以任选一个点倒水,开始bfs,如果要搜的点没有被搜到过,并且高度小于当前的点,我们就把这个点加入队列中 而 ...
- 使用Flask开发简单接口(1)--GET请求接口
前言 很多想学习接口测试的同学,可能在最开始的时候,常常会因没有可以练习的项目而苦恼,毕竟网上可以练习的接口项目不多,有些可能太简单了,有些可能又太复杂了,或者是网上一些免费接口请求次数有限制,最终导 ...