Unity uses FTP to upload and download files

1. Create a new script and name it "FTPUpDown". Copy and paste the following code.

using System;
using System.IO;
using System.Net;
using UnityEngine;

public class FTPUpDown : MonoBehaviour
{
    
    
    // 根据FTP用户名和密码创建的网络凭据
    private NetworkCredential networkCredential;
    [Header("FTP的IP路径")]
    [Tooltip("注意:端口号默认为21;")]
    [SerializeField]
    private string FTPIpPath = "ftp://0.0.0.0:21/";
    [Header(" FTP用户名")]
    [SerializeField]
    private string UserName = "abc";
    [Header(" FTP密码")]
    [SerializeField]
    private string Password = "000000";
    [Header("FTP的文件夹路径")]
    [SerializeField]
    [Tooltip("注意:IP后接的是“/www/wwwroot/”其下的FTP目录;")]
    private string FTPFolderPath = "file";
    //总的路径
    private string FTPPath
    {
    
    
        get {
    
     return FTPIpPath + FTPFolderPath; }
    }
    public static FTPUpDown a;
    private void Awake()
    {
    
    
        a = this;
        CreatNetworkCredential();
    }


    //根据用户名密码创建 “网络凭据”
    private void CreatNetworkCredential()
    {
    
    
        networkCredential = new NetworkCredential(UserName, Password);
    }
    /// <summary>
    /// FTP上传 注意设置FTP权限
    /// </summary>
    /// <param name="LoadFilePath">本地文件的路径</param>
    /// <param name="FTPPath">要上传到的FTP文件夹路径</param>
    private bool UpLoadFile(string LoadFilePath, string FTPPath)
    {
    
    
        FileInfo fileInfo = new FileInfo(LoadFilePath);
        FtpWebRequest request = CreateFtpWebRequest(FTPPath + Path.GetFileName(LoadFilePath), WebRequestMethods.Ftp.UploadFile);
        int buffLength = 2048;//一次要读取和写入多少个字节
        byte[] buff = new byte[buffLength];//写入的字节
        int contentLen;
        FileStream fs = fileInfo.OpenRead();//读取文件,将文件转换成字节文件
        Stream strm = request.GetRequestStream();
        try
        {
    
    
            contentLen = fs.Read(buff, 0, buffLength);//读取文件2048个字节,偏移为0,并赋值给buff字节组;
            while (contentLen != 0)
            {
    
    
                strm.Write(buff, 0, contentLen); //重点方法,将流写入
                contentLen = fs.Read(buff, 0, buffLength);
            }
            fs.Close();
            strm.Close();
        }
        catch (Exception ex)
        {
    
    
            return false;
            throw new Exception(ex.Message);
        }
        return true;

    }
    /// <summary>
    /// FTP下载 注意设置FTP权限
    /// </summary>
    /// <param name="FTPFilePath">要下载的FTP文件的路径</param>
    /// <param name="LoadPath">本地文件夹的路径</param>
    private bool DownloadFile(string FTPFilePath, string LocalPath)
    {
    
    
        try
        {
    
    
            FtpWebRequest request = CreateFtpWebRequest(FTPFilePath, WebRequestMethods.Ftp.DownloadFile);
            FtpWebResponse response = GetFtpResponse(request);
            FileStream filestream = File.Create(LocalPath + Path.GetFileName(FTPFilePath));
            Stream responseStream = response.GetResponseStream();
            int buflength = 2048;
            byte[] buffer = new byte[buflength];
            int bytesRead;
            bytesRead = responseStream.Read(buffer, 0, buflength);
            while (bytesRead != 0)
            {
    
    
                filestream.Write(buffer, 0, bytesRead);
                bytesRead = responseStream.Read(buffer, 0, buflength);
            }
            responseStream.Close();
            filestream.Close();
        }
        catch (WebException ex)
        {
    
    
            return false;
            throw new Exception(ex.Message);
        }
        return true;
    }
    #region 与服务器的交互
    //创建FTP连接
    public FtpWebRequest CreateFtpWebRequest(string uri, string requestMethod)
    {
    
    
        FtpWebRequest request = (FtpWebRequest)WebRequest.Create(uri);
        request.Credentials = networkCredential;
        request.KeepAlive = true;//请求完成后是否保持活动状态,不断开连接
        request.UseBinary = true;//指示服务器要传输的二进制数据
        request.UsePassive = true;//被动
        request.Method = requestMethod;
        return request;
    }
    // 获取服务器返回的响应体
    public FtpWebResponse GetFtpResponse(FtpWebRequest request)
    {
    
    
        FtpWebResponse response = null;
        try
        {
    
    
            response = (FtpWebResponse)request.GetResponse();
            return response;
        }
        catch (WebException ex)
        {
    
    
            throw new Exception("Ftphelper Upload Error --> " + ex.Message);
        }

    }
    #endregion

    //P————————————————————————————————————————————————

    /// <summary>
    /// 下载文件,或上传文件到XML文件夹
    /// </summary>

    [Header("要上传或下载的StreamingAssets文件夹下的文件名称")]
    public string FileName = "User.xml";

    [ContextMenu("下载到StreamingAssets文件夹下")]
    public void DownXMLToStreaming()
    {
    
    
        if (!System.IO.Directory.Exists(Application.streamingAssetsPath))
        {
    
    
            Directory.CreateDirectory(Application.streamingAssetsPath);
            UnityEditor.AssetDatabase.Refresh();
        }

        DownloadFile(FTPPath + FileName, Application.streamingAssetsPath);
        UnityEditor.AssetDatabase.Refresh();
        print("下载完成!");
    }
    [ContextMenu("上传到FTP服务器")]
    public void UpLoadXML()
    {
    
    
        if (!System.IO.Directory.Exists(Application.streamingAssetsPath))
        {
    
    
            Directory.CreateDirectory(Application.streamingAssetsPath);
            UnityEditor.AssetDatabase.Refresh();
            Debug.LogError("没有文件");
            return;
        }
        if (!File.Exists(Application.streamingAssetsPath + "/" + FileName))
        {
    
    
            Debug.LogError("没有文件");
            return;
        }

        UpLoadFile(Application.streamingAssetsPath + "/" + FileName, FTPPath);
        print("上传完成!");
    }
}

2. Create a new StreamingAssets folder, the file downloaded by FTP will appear in this directory; uploading also needs to put the file here. Hang the script on any object, after configuring the script variables, right-click the script to test, if there is a problem, take a closer look at the prompt description of the script variable, I have nothing wrong with the test here!
Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_44003637/article/details/114983240