2018年5月11日 星期五

Unity內將檔案上傳到FTP

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

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

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

使用WebClient的第一種:
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using System.Net;
  4. using System.Threading;
  5. using UnityEngine;
  6.  
  7. public class XXX : MonoBehaviour
  8. {
  9. void Start()
  10. {
  11. StartCoroutine(FTPUpload1());
  12. }
  13. void Update()
  14. {
  15.  
  16. }
  17. IEnumerator FTPUpload1()
  18. {
  19. var filename = "D:/XXX.png";
  20. bool isUploading = false;
  21.  
  22. UnityEngine.Debug.Log("開始!!");
  23.  
  24. ThreadPool.QueueUserWorkItem((o) =>
  25. {
  26. using (WebClient client = new WebClient())
  27. {
  28. client.Credentials = new NetworkCredential("kim", "123");
  29. client.UploadFile("ftp://127.0.0.1/XXX.png", "STOR", filename);
  30. }
  31. isUploading = true;
  32. });
  33.  
  34. while (!isUploading)
  35. {
  36. UnityEngine.Debug.Log("上傳中!!");
  37. yield return new WaitForSeconds(0.1f);
  38. }
  39.  
  40. UnityEngine.Debug.Log("結束!!");
  41. }
  42. }

使用ftpWebRequest的第二種:
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Net;
  5. using System.Threading;
  6. using UnityEngine;
  7.  
  8. public class XXX : MonoBehaviour
  9. {
  10. void Start()
  11. {
  12. StartCoroutine(FTPUpload2());
  13. }
  14. void Update()
  15. {
  16.  
  17. }
  18. IEnumerator FTPUpload2()
  19. {
  20. var filename = "D:/XXX.png";
  21. bool isUploading = false;
  22.  
  23. UnityEngine.Debug.Log("開始!!");
  24.  
  25. ThreadPool.QueueUserWorkItem((o) =>
  26. {
  27. FtpWebRequest ftpWebRequest = (FtpWebRequest)WebRequest.Create("ftp://127.0.0.1/XXX.png");
  28.  
  29. ftpWebRequest.Method = WebRequestMethods.Ftp.UploadFile;
  30. ftpWebRequest.Credentials = new NetworkCredential("kim", "123");
  31. ftpWebRequest.UsePassive = true;
  32. ftpWebRequest.UseBinary = true;
  33. ftpWebRequest.KeepAlive = true;
  34.  
  35. StreamReader sourceStream = new StreamReader(filename);
  36. byte[] fileBytes = File.ReadAllBytes(filename);
  37. sourceStream.Close();
  38. ftpWebRequest.ContentLength = fileBytes.Length;
  39.  
  40. Stream requestStream = ftpWebRequest.GetRequestStream();
  41. requestStream.Write(fileBytes, 0, fileBytes.Length);
  42. requestStream.Close();
  43.  
  44. FtpWebResponse ftpWebResponse = (FtpWebResponse)ftpWebRequest.GetResponse();
  45. ftpWebResponse.Close();
  46.  
  47. isUploading = true;
  48. });
  49.  
  50. while (!isUploading)
  51. {
  52. UnityEngine.Debug.Log("上傳中!!");
  53. yield return new WaitForSeconds(0.1f);
  54. }
  55.  
  56. UnityEngine.Debug.Log("結束!!");
  57. }
  58. }