[ASP.NET]web实现用FTP上传、下载文件(附源码)
文章配套源码下载地址:https://download.csdn.net/download/djk8888/10486581
index.aspx 页:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="index.aspx.cs" Inherits="index" %><!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server"><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>ASP.NET的FTP上传和下载</title><script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body><form id="form1" runat="server"><div><asp:FileUpload runat="server" ID="FileUpload"></asp:FileUpload> <asp:Button ID="Button1" runat="server" Text="FTP上传" OnClick="Button1_Click" /> <asp:Button ID="Button2" runat="server" Text="刷新列表" OnClick="Button2_Click" /><br /><br /><table border="1" width="1000"><tr><th>编号</th><th>文件夹</th><th>文件名</th><th>日期</th><th>http协议下载</th><th>ftp协议下载</th></tr><asp:Repeater runat="server" ID="Repeater1"><ItemTemplate><tr><td><%#Eval("fileNo") %></td><td><%#Eval("ftpURI") %></td><td><%#Eval("fileName") %></td><td><%#Eval("datetime") %></td><td><a target="_blank" href='http://djk8888csdn.3vcm.net/<%#Eval("ftpURI") %>/<%#Eval("fileName") %>'>http://djk8888csdn.3vcm.net/<%#Eval("ftpURI") %>/<%#Eval("fileName") %></a></td> <td><input type="button" value="下载" onclick=ftpDownload('<%#Eval("ftpURI") %>','<%#Eval("fileName") %>') /></td></tr></ItemTemplate></asp:Repeater></table></div></form>
</body>
</html>
<script type="text/javascript">function ftpDownload(uri, name) {$.get("ftpDownload.ashx",{ ftpURI: uri, fileName: name },function (e) {if (e == "ok") {alert("下载成功!文件在:\r\n C:\\" + name);}else {alert("下载失败:\r\n" + e);}});}
</script>
index.aspx.cs 页:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;/// <summary>
/// 这是一个完整的例子
/// </summary>
public partial class index : System.Web.UI.Page
{static string strfile = "info.txt";//txt文件名string txtPath = HttpContext.Current.Server.MapPath(strfile);//相对路径转绝对路径string strout = string.Empty;//txt文件里读出来的内容 protected void Page_Load(object sender, EventArgs e){if (!IsPostBack){Bind();}}//刷新列表protected void Button2_Click(object sender, EventArgs e){Bind();}private void Bind(){//string txt = File.ReadAllText(txtPath, Encoding.Default);//如果txt内容较少可用此法 if (File.Exists(txtPath)){using (StreamReader sr = new StreamReader(System.Web.HttpContext.Current.Server.MapPath(strfile), System.Text.Encoding.Default)){strout = sr.ReadToEnd();string temp = strout.Replace("\r\n", "");string[] strArr = temp.Split(';');//分解每一组数据 if (strArr != null && strArr.Any()){int fileNo = 1;List<Info> list = new List<Info>();foreach (var item in strArr){if (!string.IsNullOrEmpty(item) && !string.IsNullOrWhiteSpace(item)){string[] strArr2 = item.Split('|');//分解每一个属性Info info = new Info();info.fileNo = fileNo; fileNo++;info.ftpURI = strArr2[0].ToString();info.fileName = strArr2[1].ToString();info.datetime = DateTime.Parse(strArr2[2].ToString());list.Add(info);}}if (list != null && list.Any()){this.Repeater1.DataSource = list.OrderByDescending(a => a.datetime);this.Repeater1.DataBind();}}}}}protected void Button1_Click(object sender, EventArgs e){string errorMsg = "";if (FileUpload.HasFile){int fileLength = FileUpload.PostedFile.ContentLength;//文件大小,单位bytestring fileName = Path.GetFileName(FileUpload.PostedFile.FileName);//文件名称string extension = Path.GetExtension(FileUpload.PostedFile.FileName).ToLower();//文件扩展名//限制上传文件最大不能超过500M if (!(fileLength < 512 * 1024 * 1024)){Response.Write("<script>alert('文件最大不能超过500M!');</script>");return;}//限制文件格式if (!".doc.docx.xls.xlsx.pdf.txt.jpg.jpeg".Contains(extension)){Response.Write("<script>alert('不支持的文件格式!');</script>");return;}//创建文件夹string ftpURI = DateTime.Now.ToString("yyyyMMdd");//以日期作为文件夹名称try{FtpWeb.CreateDirectory(ftpURI);//创建文件夹}catch { }//准备上传文件Stream fileStream = null;try{fileStream = FileUpload.PostedFile.InputStream;//读取本地文件流var b = FtpWeb.Upload(ftpURI, fileName, fileLength, fileStream, out errorMsg);//开始上传if (b){if (File.Exists(txtPath)){FileStream myStream = new FileStream(txtPath, FileMode.Append, FileAccess.Write);// FileMode.Append,追加一行数据StreamWriter sw = new StreamWriter(myStream);sw.WriteLine(ftpURI + "|" + fileName + "|" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ";");//写入文件sw.Close();}Bind();Response.Write("<script>alert('上传成功!');</script>");}else{Response.Write("<script>alert('上传失败!" + errorMsg + "');</script>");}}catch (Exception ex){Response.Write("<script>alert('上传失败!" + ex.ToString() + "');</script>");}finally{if (fileStream != null) fileStream.Close();}}else{Response.Write("<script>alert('请选择一个文件再上传!');</script>");}}public class Info{public int fileNo { get; set; }public string ftpURI { get; set; }public string fileName { get; set; }public DateTime datetime { get; set; }}
}
ftpDownload.ashx 页:
<%@ WebHandler Language="C#" Class="ftpDownload" %>using System;
using System.Web;public class ftpDownload : IHttpHandler
{/// <summary>/// ftp协议下载文件/// </summary>/// <param name="context"></param>public void ProcessRequest(HttpContext context){context.Response.ContentType = "text/plain";string ftpURI = context.Request.QueryString["ftpURI"];//ftpURIstring fileName = context.Request.QueryString["fileName"];//fileNamestring localPath = "C:\\";//文件下载路径(可自定义)string errorMsg = "";bool b = FtpWeb.Download(ftpURI, localPath, fileName, out errorMsg);if (b){context.Response.Write("ok");}else{context.Response.Write(errorMsg);}}public bool IsReusable{get{return false;}}
}
FtpWeb.cs 页:
using System;
using System.IO;
using System.Net;/// <summary>
/// web地址: http://djk8888csdn.3vcm.net/
/// FTP地址: ftp://013.3vftp.com/
/// FTP账号: djk8888csdn
/// FTP密码: 123456
/// </summary>
public class FtpWeb
{public static string ftpHost = "ftp://013.3vftp.com/";//FTP的ip地址或域名 public static string ftpUserID = "djk8888csdn";//ftp账号public static string ftpPassword = "123456";//ftp密码/// <summary>/// 上传/// </summary>/// <param name="ftpURI">ftp上的路径</param>/// <param name="filename">ftp上的文件名</param>/// <param name="fileLength">文件大小</param>/// <param name="localStream">本地文件流</param>/// <param name="errorMsg">报错信息</param>/// <returns></returns>public static bool Upload(string ftpURI, string filename, int fileLength, Stream localStream, out string errorMsg){errorMsg = "";Stream fileStream = null;//本地文件流Stream requestStream = null;//ftp文件流 try{fileStream = localStream;//本地文件流Uri uri = new Uri(ftpHost + ftpURI + "/" + filename);//ftp完整路径FtpWebRequest uploadRequest = (FtpWebRequest)WebRequest.Create(uri);//创建FtpWebRequest实例uploadRequest uploadRequest.Method = WebRequestMethods.Ftp.UploadFile;//将FtpWebRequest属性设置为上传文件 uploadRequest.Credentials = new NetworkCredential(ftpUserID, ftpPassword);//认证FTP用户名密码 requestStream = uploadRequest.GetRequestStream();//ftp上的空文件int buffLength = 2048; //开辟2KB缓存区 byte[] buff = new byte[buffLength];int contentLen;contentLen = fileStream.Read(buff, 0, buffLength);while (contentLen != 0){requestStream.Write(buff, 0, contentLen);//将本地文件流写入到ftp上的空文件中去contentLen = fileStream.Read(buff, 0, buffLength);}requestStream.Close();fileStream.Close();return true;}catch (Exception ex){errorMsg = ex.Message;return false;}finally{if (fileStream != null) fileStream.Close();if (requestStream != null) requestStream.Close();}}//创建文件夹public static string CreateDirectory(string ftpDir){FtpWebRequest request = SetFtpConfig(WebRequestMethods.Ftp.MakeDirectory, ftpDir);FtpWebResponse response = (FtpWebResponse)request.GetResponse();return response.StatusDescription;}private static FtpWebRequest SetFtpConfig(string method, string ftpDir){return SetFtpConfig(method, ftpDir, "");}private static FtpWebRequest SetFtpConfig(string method, string ftpDir, string fileName){ftpDir = string.IsNullOrEmpty(ftpDir) ? "" : ftpDir.Trim();return SetFtpConfig(ftpHost, ftpUserID, ftpPassword, method, ftpDir, fileName);}private static FtpWebRequest SetFtpConfig(string host, string username, string password, string method, string RemoteDir, string RemoteFileName){System.Net.ServicePointManager.DefaultConnectionLimit = 50;FtpWebRequest request = (FtpWebRequest)WebRequest.Create(host + RemoteDir + "/" + RemoteFileName);request.Method = method;request.Credentials = new NetworkCredential(username, password);request.UsePassive = false;request.UseBinary = true;request.KeepAlive = false;return request;}/// <summary>/// FTP文件下载(代码仅供参考)/// </summary>/// <param name="ftpURI">fpt文件路径</param>/// <param name="localPath">本地文件路径</param>/// <param name="fileName">ftp文件名</param>/// <param name="errorMsg">报错信息</param>/// <returns></returns>public static bool Download(string ftpURI, string localPath, string fileName, out string errorMsg){errorMsg = "";FtpWebRequest reqFTP = null;FileStream outputStream = null;Stream ftpStream = null;FtpWebResponse response = null;try{outputStream = new FileStream(localPath + "/" + fileName, FileMode.Create);//创建本地空文件Uri uri = new Uri(ftpHost + ftpURI + "/" + fileName);//ftp完整路径reqFTP = (FtpWebRequest)FtpWebRequest.Create(uri);reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;reqFTP.UseBinary = true;reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);//登录ftpresponse = (FtpWebResponse)reqFTP.GetResponse();ftpStream = response.GetResponseStream();//读取ftp上文件流long cl = response.ContentLength;int bufferSize = 2048;//缓冲int readCount;byte[] buffer = new byte[bufferSize];readCount = ftpStream.Read(buffer, 0, bufferSize);while (readCount > 0){outputStream.Write(buffer, 0, readCount);//将ftp文件流写入到本地空文件中去readCount = ftpStream.Read(buffer, 0, bufferSize);}return true;}catch (Exception ex){errorMsg = ex.Message;return false;}finally{if (ftpStream != null) ftpStream.Close();if (outputStream != null) outputStream.Close();if (response != null) response.Close();}}
}
文章配套源码下载地址:https://download.csdn.net/download/djk8888/10486581
winform的ftp上传下载:https://blog.csdn.net/djk8888/article/details/80662238
[ASP.NET]web实现用FTP上传、下载文件(附源码)相关推荐
- ftp上传-下载文件通用工具类,已实测
话不多说直接上代码 package com.springboot.demo.utils;import lombok.extern.slf4j.Slf4j; import org.apache.comm ...
- python get 下载 目录_python实现支持目录FTP上传下载文件的方法
本文实例讲述了python实现支持目录FTP上传下载文件的方法.分享给大家供大家参考.具体如下: 该程序支持ftp上传下载文件和目录.适用于windows和linux平台. #!/usr/bin/en ...
- python上传本地文件到ftp_python实现的简单FTP上传下载文件实例
本文实例讲述了python实现的简单FTP上传下载文件的方法.分享给大家供大家参考.具体如下: python本身自带一个FTP模块,可以实现上传下载的函数功能. #!/usr/bin/env pyth ...
- android ftp同步程序,ftp同步 安卓,安卓手机ftp上传下载文件功能同步视频照片
手机拍照越来方便,手机里的照片也越积越多,手机运行缓慢,本文利用安卓的每步FTP服务APP来自动实现手机视频照片的同步,释放手机被占用的存储空间.在机顶盒上运行每步FTP服务,机顶盒USB口连接U盘做 ...
- bat定时进行ftp上传下载文件
bat进行ftp上传下载文件 参考文章: https://blog.csdn.net/yongzai666/article/details/86488761 背景: 由于公司某个系统原本硬盘损坏 , ...
- KindEditor ASP.NET 上传/浏览服务器 附源码
KindEditor是一个不错的网页在线编辑器, 早就想把它用在自己的项目中 可是它只提供了asp,hp,jsp上传的类, 没有提供Asp.net的上传和浏览程序. 当时看的是PHP的搞的一头雾水.. ...
- java ftp上传文件_jaVA使用FTP上传下载文件的问题
为了实现 FTP上传下载,大概试了两个方法 sun.net.ftp.FtpClient org.apache.commons.net 一开始使用sun.net.ftp.FtpClient,结果发现唯一 ...
- ftp上传下载文件详解
首先导入包 import org.apache.commons.NET.ftp.FTPClient; import org.apache.commons.net.ftp.FTPFile; FTPCli ...
- linux运行shellftp上传文件,shell脚本实现ftp上传下载文件
前段时间工作中需要将经过我司平台某些信息核验数据提取后上传到客户的FTP服务器上,以便于他们进行相关的信息比对核验.由于包含这些信息的主机只有4台,采取的策略是将生成的4个文件汇集到一个主机上,然后在 ...
最新文章
- AI战场,李彦宏马化腾马云都在频频刷脸,周鸿祎和他的360在想啥呢?
- Xamarin.Forms开发实战基础篇大学霸内部资料
- java对象交互_Java 2 对象交互
- 第一章 基础算法 【完结】
- 【MM模块】 External Services 外部服务
- kickstart 安装CentOS GPT分区的完整ks示例
- python缩进符错误_python – 如何修复Pylint“错误的缩进”和PEP8 E121?
- Android之OKHttp使用总结
- ubuntu 下安装mplayer
- asp net服务器虚拟路径,asp.net获取服务器虚拟路径
- 经典算法——单向链表反转
- 一个完整的pytorch预训练实现图像分类,模型融合
- python凹多边形分割_凹多边形分割成凸多边形
- 支付宝对账单接口对接
- win10 运行debussy不能打开波形窗口问题
- 四十七、使用bootstrap中的选项卡制作产品特色页面
- python+HTMLTable,生成html表格
- Java 13---JDBC简介
- Java简单搭建免签个人支付宝当面付收款接口,无需挂APP,官方接口无风险
- 肯德基门店 csv