2018年5月11日 星期五

Unity內將檔案上傳到FTP

在做專案時有時會需要將檔案上傳到FTP去,像是照片或影片等,所以這邊便記錄一下做法。

我分別遇過需上傳到一般FTP、SFTP和使用主動模式FTP的情況,因此實做過三種方式:FTP的兩種,SFTP和使用主動模式FTP的一種。

這邊只記錄FTP的兩種,第三種有點麻煩,之後有空整理再另外放上來。

使用WebClient的第一種:
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Threading;
using UnityEngine;

public class XXX : MonoBehaviour
{
    void Start()
    {
        StartCoroutine(FTPUpload1());
    }
    
    void Update()
    {

    }
    
    IEnumerator FTPUpload1()
    {
        var filename = "D:/XXX.png";
        bool isUploading = false;

        UnityEngine.Debug.Log("開始!!");

        ThreadPool.QueueUserWorkItem((o) =>
        {
            using (WebClient client = new WebClient())
            {
                client.Credentials = new NetworkCredential("kim", "123");
                client.UploadFile("ftp://127.0.0.1/XXX.png", "STOR", filename);
            }
            isUploading = true;
        });

        while (!isUploading)
        {
            UnityEngine.Debug.Log("上傳中!!");
            yield return new WaitForSeconds(0.1f);
        }

        UnityEngine.Debug.Log("結束!!");
    }
}

使用ftpWebRequest的第二種:
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Threading;
using UnityEngine;

public class XXX : MonoBehaviour
{
    void Start()
    {
        StartCoroutine(FTPUpload2());
    }
    
    void Update()
    {

    }
    
    IEnumerator FTPUpload2()
    {
        var filename = "D:/XXX.png";
        bool isUploading = false;

        UnityEngine.Debug.Log("開始!!");

        ThreadPool.QueueUserWorkItem((o) =>
        {
            FtpWebRequest ftpWebRequest = (FtpWebRequest)WebRequest.Create("ftp://127.0.0.1/XXX.png");

            ftpWebRequest.Method = WebRequestMethods.Ftp.UploadFile;
            ftpWebRequest.Credentials = new NetworkCredential("kim", "123");
            ftpWebRequest.UsePassive = true;
            ftpWebRequest.UseBinary = true;
            ftpWebRequest.KeepAlive = true;

            StreamReader sourceStream = new StreamReader(filename);
            byte[] fileBytes = File.ReadAllBytes(filename);
            sourceStream.Close();
            ftpWebRequest.ContentLength = fileBytes.Length;

            Stream requestStream = ftpWebRequest.GetRequestStream();
            requestStream.Write(fileBytes, 0, fileBytes.Length);
            requestStream.Close();

            FtpWebResponse ftpWebResponse = (FtpWebResponse)ftpWebRequest.GetResponse();
            ftpWebResponse.Close();

            isUploading = true;
        });

        while (!isUploading)
        {
            UnityEngine.Debug.Log("上傳中!!");
            yield return new WaitForSeconds(0.1f);
        }

        UnityEngine.Debug.Log("結束!!");
    }
}

沒有留言:

張貼留言