Unity(十七) 在Unity中Android使用FTP进行上传、下载、文件创建(客户端部分)
参考链接:https://www.cnblogs.com/zhenzaizai/p/7434669.html
感谢原作,并修正判断文件夹是否存在的问题
如何在Win10上创建FTP服务器 :https://jingyan.baidu.com/article/0bc808fc408fa91bd585b94f.html 来自百度经验(需要电脑是专业版系统才有【用户和组】选项)
FTP模块
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using UnityEngine;
using UnityEngine.UI;namespace UpLoad
{class UpLoadFiles{private static string FTPCONSTR = "ftp://192.168.xxx.136/";//FTP的服务器地址,格式为ftp://192.168.1.234/。ip地址和端口换成自己的,这些建议写在配置文件中,方便修改private static string FTPUSERNAME = "test";//我的FTP服务器的用户名private static string FTPPASSWORD = "123456";//我的FTP服务器的密码public static float uploadProgress;//上传进度public static float downloadProgress;//下载进度#region 本地文件上传到FTP服务器/// <summary>/// 文件上传到ftp/// </summary>/// <param name="ftpPath">ftp的文件路径</param>/// <param name="localPath">本地的文件目录</param>/// <param name="fileName">可重命名文件</param>/// <param name="pb">进度条</param>/// <returns></returns>public static bool UploadFiles(string ftpPath, string localPath, string fileName){//path = "ftp://" + UserUtil.serverip + path;string erroinfo = "";float percent = 0;FileInfo f = new FileInfo(localPath);localPath = localPath.Replace("\\", "/");bool b = MakeDir(ftpPath);if (b == false){return false;}localPath = FTPCONSTR + ftpPath + fileName;FtpWebRequest reqFtp = (FtpWebRequest)FtpWebRequest.Create(new Uri(localPath));reqFtp.UseBinary = true;reqFtp.Credentials = new NetworkCredential(FTPUSERNAME, FTPPASSWORD);reqFtp.KeepAlive = false;reqFtp.Method = WebRequestMethods.Ftp.UploadFile;reqFtp.ContentLength = f.Length;int buffLength = 2048;byte[] buff = new byte[buffLength];int contentLen;FileStream fs = f.OpenRead();int allbye = (int)f.Length;int startbye = 0;try{Stream strm = reqFtp.GetRequestStream();contentLen = fs.Read(buff, 0, buffLength);while (contentLen != 0){strm.Write(buff, 0, contentLen);startbye = contentLen + startbye;percent = (float)startbye / (float)allbye * 100;if (percent <= 100){//Debug.Log(percent);uploadProgress = percent;}contentLen = fs.Read(buff, 0, buffLength);}strm.Close();fs.Close();erroinfo = "完成";return true;}catch (Exception ex){erroinfo = string.Format("因{0},无法完成上传", ex.Message);return false;}}#endregion#region 从ftp服务器下载文件/// <summary>/// 从ftp服务器下载文件的功能----带进度条/// </summary>/// <param name="ftpfilepath">ftp下载的地址</param>/// <param name="filePath">保存本地的地址</param>/// <param name="fileName">保存的名字</param>/// <param name="pb">进度条引用</param>/// <returns></returns>public static bool Download(string ftpfilepath, string filePath, string fileName){FtpWebRequest reqFtp = null;FtpWebResponse response = null;Stream ftpStream = null;FileStream outputStream = null;try{filePath = filePath.Replace("我的电脑\\", "");String onlyFileName = Path.GetFileName(fileName);string newFileName = filePath + onlyFileName;if (File.Exists(newFileName)){try{File.Delete(newFileName);}catch { }}ftpfilepath = ftpfilepath.Replace("\\", "/");string url = FTPCONSTR + ftpfilepath;reqFtp = (FtpWebRequest)FtpWebRequest.Create(new Uri(url));reqFtp.UseBinary = true;reqFtp.Credentials = new NetworkCredential(FTPUSERNAME, FTPPASSWORD);response = (FtpWebResponse)reqFtp.GetResponse();ftpStream = response.GetResponseStream();long cl = GetFileSize(url);int bufferSize = 2048;int readCount;byte[] buffer = new byte[bufferSize];readCount = ftpStream.Read(buffer, 0, bufferSize);outputStream = new FileStream(newFileName, FileMode.Create);float percent = 0;while (readCount > 0){outputStream.Write(buffer, 0, readCount);readCount = ftpStream.Read(buffer, 0, bufferSize);percent = (float)outputStream.Length / (float)cl * 100;if (percent <= 100){// Debug.Log(percent);downloadProgress = percent;}}return true;}catch (Exception ex){Debug.LogError("因{0},无法下载"+ex.Message);return false;}finally{if (reqFtp != null)reqFtp.Abort();if (response != null)response.Close();if (ftpStream != null)ftpStream.Close();if (outputStream != null)outputStream.Close();}}#endregion#region 获得文件的大小/// <summary>/// 获得文件大小/// </summary>/// <param name="url">FTP文件的完全路径</param>/// <returns></returns>public static long GetFileSize(string url){long fileSize = 0;try{FtpWebRequest reqFtp = (FtpWebRequest)FtpWebRequest.Create(new Uri(url));reqFtp.UseBinary = true;reqFtp.Credentials = new NetworkCredential(FTPUSERNAME, FTPPASSWORD);reqFtp.Method = WebRequestMethods.Ftp.GetFileSize;FtpWebResponse response = (FtpWebResponse)reqFtp.GetResponse();fileSize = response.ContentLength;response.Close();}catch (Exception ex){Debug.LogError(ex.Message);}return fileSize;}#endregion#region 在ftp服务器上创建文件目录/// <summary>///在ftp服务器上创建文件目录/// </summary>/// <param name="dirName">文件目录</param>/// <returns></returns>public static bool MakeDir(string dirName){try{string uri=(FTPCONSTR+dirName+"/");if (DirectoryIsExist(uri)){Debug.Log("已存在");return true;} string url = FTPCONSTR + dirName;FtpWebRequest reqFtp = (FtpWebRequest)FtpWebRequest.Create(new Uri(url));reqFtp.UseBinary = true;// reqFtp.KeepAlive = false;reqFtp.Method = WebRequestMethods.Ftp.MakeDirectory;reqFtp.Credentials = new NetworkCredential(FTPUSERNAME, FTPPASSWORD);FtpWebResponse response = (FtpWebResponse)reqFtp.GetResponse();response.Close();return true;}catch (Exception ex){Debug.LogError("因{0},无法下载"+ex.Message);return false;}}/// <summary>/// 判断ftp上的文件目录是否存在/// </summary>/// <param name="path"></param>/// <returns></returns> public static bool DirectoryIsExist(string uri){string[] value = GetFileList(uri);if (value == null){return false;}else{return true;}}private static string[] GetFileList(string uri){StringBuilder result = new StringBuilder();try{FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(uri);reqFTP.UseBinary = true;reqFTP.Credentials = new NetworkCredential(FTPUSERNAME, FTPPASSWORD);reqFTP.Method = WebRequestMethods.Ftp.ListDirectoryDetails;WebResponse response = reqFTP.GetResponse();StreamReader reader = new StreamReader(response.GetResponseStream());string line = reader.ReadLine();while (line != null){result.Append(line);result.Append("\n");line = reader.ReadLine();}reader.Close();response.Close();return result.ToString().Split('\n');}catch{return null;}}#endregion#region 从ftp服务器删除文件的功能/// <summary>/// 从ftp服务器删除文件的功能/// </summary>/// <param name="fileName"></param>/// <returns></returns>public static bool DeleteFtpFile(string fileName){try{string url = FTPCONSTR + fileName;FtpWebRequest reqFtp = (FtpWebRequest)FtpWebRequest.Create(new Uri(url));reqFtp.UseBinary = true;reqFtp.KeepAlive = false;reqFtp.Method = WebRequestMethods.Ftp.DeleteFile;reqFtp.Credentials = new NetworkCredential(FTPUSERNAME, FTPPASSWORD);FtpWebResponse response = (FtpWebResponse)reqFtp.GetResponse();response.Close();return true;}catch (Exception ex){//errorinfo = string.Format("因{0},无法下载", ex.Message);return false;}}#endregion#region 从ftp服务器上获得文件夹列表/// <summary>/// 从ftp服务器上获得文件夹列表/// </summary>/// <param name="RequedstPath">服务器下的相对路径</param>/// <returns></returns>public static List<string> GetFtpDirctory(string RequedstPath){List<string> strs = new List<string>();try{string uri =FTPCONSTR+RequedstPath; //根路径+路径FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));// ftp用户名和密码reqFTP.Credentials = new NetworkCredential(FTPUSERNAME, FTPPASSWORD);reqFTP.Method = WebRequestMethods.Ftp.ListDirectoryDetails;WebResponse response = reqFTP.GetResponse();StreamReader reader = new StreamReader(response.GetResponseStream());//中文文件名string line = reader.ReadLine();while (line != null){if (line.Contains("<DIR>")){string msg = line.Substring(line.LastIndexOf("<DIR>") + 5).Trim();strs.Add(msg);}line = reader.ReadLine();}reader.Close();response.Close();return strs;}catch (Exception ex){Console.WriteLine("获取目录出错:" + ex.Message);}return strs;}#endregion#region 从ftp服务器上获得文件列表/// <summary>/// 从ftp服务器上获得文件列表/// </summary>/// <param name="RequedstPath">服务器下的相对路径</param>/// <returns></returns>public static List<string> GetFtpFiles(string RequedstPath){List<string> strs = new List<string>();try{string uri = FTPCONSTR + RequedstPath; //根路径+路径FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));// ftp用户名和密码reqFTP.Credentials = new NetworkCredential(FTPUSERNAME, FTPPASSWORD);reqFTP.Method = WebRequestMethods.Ftp.ListDirectoryDetails;WebResponse response = reqFTP.GetResponse();StreamReader reader = new StreamReader(response.GetResponseStream());//中文文件名string line = reader.ReadLine();while (line != null){if (!line.Contains("<DIR>")){string msg = line.Substring(39).Trim();strs.Add(msg);}line = reader.ReadLine();}reader.Close();response.Close();return strs;}catch (Exception ex){Console.WriteLine("获取文件出错:" + ex.Message);}return strs;} #endregion
}
}
测试调用
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using UnityEngine;
using UnityEngine.UI;
using UpLoad;public class Test : MonoBehaviour {void Start () {//上传n//new Thread(UpLoad).Start();//下载new Thread(DownLoad).Start();//创建//bool bl=UpLoadFiles.MakeDir("AaaaAb"); //删除//UpLoadFiles.DeleteFtpFile("/data/uploadFile/a.zip");//得到文件夹列表//List<string> dirs = UpLoadFiles.GetFtpDirctory("");//得到文件列表//List<string> files = UpLoadFiles.GetFtpFiles("");}void UpLoad(){//路径来自 "ftp://192.168.xxx.136/data/uploadFile/a.zip"UpLoadFiles.UploadFiles("/data/uploadFile/", "d:/Test2/a.zip", "b.zip");}void DownLoad(){UpLoadFiles.Download("/data/uploadFile/a.zip", "d:/Test2/", "C.zip");}}
Unity(十七) 在Unity中Android使用FTP进行上传、下载、文件创建(客户端部分)相关推荐
- java ftp ftpclient_详解JAVA中使用FTPClient工具类上传下载
详解JAVA中使用FTPClient工具类上传下载 在Java程序中,经常需要和FTP打交道,比如向FTP服务器上传文件.下载文件.本文简单介绍如何利用jakarta commons中的FTPClie ...
- Linux 终端访问 FTP 及 上传下载 文件
今天同事问我一个问题,在Linux 下访问FTP,并将文件上传上去. 我之前一直是用WinSCP工具的. 先将文件从linux copy到windows下,然后在传到ftp上. google 一下. ...
- Linux 终端訪问 FTP 及 上传下载 文件
今天同事问我一个问题,在Linux 下訪问FTP,并将文件上传上去. 我之前一直是用WinSCP工具的. 先将文件从linux copy到windows下,然后在传到ftp上. google 一下. ...
- ftp文件推送 linux_Linux 终端访问 FTP 及 上传下载 文件
今天同事问我一个问题,在Linux 下访问FTP,并将文件上传上去. 我之前一直是用WinSCP工具的. 先将文件从linux copy到windows下,然后在传到ftp上.google 一下. 方 ...
- java ftp 下载慢_Java实现ftp文件上传下载解决慢中文乱码多个文件下载等问题
废话不多说了,直接给大家贴代码了,具体代码如下所示: //文件上传 public static boolean uploadToFTP(String url,int port,String usern ...
- 关于FileZilla连接FTP站点上传下载文件
关于FileZilla连接FTP站点上传下载文件 浏览器搜索FileZilla官网:https://www.filezilla.cn/download 根据自己操作系统安装 安装完成之后的启动界面是这 ...
- C++:FTP文件上传下载(附完整源码)
C++:FTP文件上传下载 FTP文件下载 FTP文件上传 FTP文件下载 #include #include #include #pragma comment(lib, "WinInet. ...
- [转]文件传输协议(FTP)操作(上传,下载,新建,删除,FTP间传送文件等)实现汇总1
转自:http://blog.csdn.net/soarheaven/archive/2008/12/08/3474152.aspx 最近项目需要对FTP服务器进行操作,现把实现总结如下: 打算分2篇 ...
- JAVA中使用FTPClient实现文件上传下载
在JAVA程序中,经常需要和FTP打交道,比如向FTP服务器上传文件.下载文件,本文简单介绍如何利用jakarta commons中的FTPClient(在commons-net包中)实现上传下载文件 ...
最新文章
- 如何在MFC中使用cout和printf,输出到控制台
- 44、【华为HCIE-Storage】--InfoEqualizer
- java gc原理_Java内存管理以及GC工作原理
- 2022年大厂面试八股文上线!
- mui汉字图标_MUI从入门到项目实战(三)增加自定义icon图标
- Openresty 预编译安装教程
- 用python批量创建docker_「docker实战篇」python的docker-docker镜像的创建使用dockerfile(3...
- 【labelme】改造labelme
- 支持向量机python代码_Python中的支持向量机SVM的使用(有实例)
- 电影网址导航V20201218版源码
- MIT黑科技:无需视觉输入,立体声音频+摄像机元数据即可实现移动车辆定位
- 实体商店与虚拟商店购买保护流程:
- SharePoint 2013技巧分享系列 - 隐藏Blog和Apps左侧导航菜单
- 多个安卓设备投屏到电脑_手机投屏软件哪个好,如何将手机屏幕投屏到电脑?...
- Elgamal数字签名原理
- python 正则表达式量词
- 用VB创建一个对象数组
- [译]Hierarchical Macro Strategy Model for MOBA Game AI(王者荣耀)--翻译
- 工程化框架之feather
- 怎样用word制作标准格式公文操作实例