1. 程式人生 > 其它 >unity儲存字串內容到伺服器ftp站點

unity儲存字串內容到伺服器ftp站點

目標是將unity場景資料直接儲存在測試伺服器某資料夾內,儲存為json格式。

因為用IIS只部署了一個簡單的伺服器,使用UnityWebRequest上傳檔案方式不行,所以建立了ftp站點並用FtpWebRequest實現上傳。

using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using UnityEngine;
namespace UPLoadFTP
{
    class UpLoadFiles
    {
        private
static string FTPCONSTR = "ftp://XXX.XXX.XXX.XXX/";//FTP的伺服器地址格式(ftp://192.168.1.234/)。ip地址和埠換成自己的,這些建議寫在配置檔案中,方便修改 private static string FTPUSERNAME = "Upload";//我的FTP伺服器的使用者名稱 private static string FTPPASSWORD = "1234";//我的FTP伺服器的密碼 /// <summary> /// 儲存字串內容到FTP /// </summary>
/// <param name="ftpPath">儲存上傳檔案的ftp路徑</param> /// <param name="fileName">上傳檔名稱</param> /// <returns></returns> public static bool UploadFiles(string ftpPath, string fileName) { string str = "stringContest"; byte
[] array = Encoding.ASCII.GetBytes(str); MemoryStream stream = new MemoryStream(array); string erroinfo = "";//錯誤資訊
string path; path = FTPCONSTR + ftpPath + fileName; FtpWebRequest reqFtp = (FtpWebRequest)WebRequest.Create(new Uri(path)); reqFtp.UseBinary = true;//代表可以傳送圖片 reqFtp.Credentials = new NetworkCredential(FTPUSERNAME, FTPPASSWORD); reqFtp.KeepAlive = false;//在請求完成之後是否關閉到 FTP 伺服器的控制連線 reqFtp.Method = WebRequestMethods.Ftp.UploadFile;//表示將檔案上載到 FTP 伺服器的 FTP STOR 協議方法 reqFtp.ContentLength = stream.Length;//本地上傳檔案的長度 int buffLength = 2048;//緩衝區大小 byte[] buff = new byte[buffLength];//緩衝區 int contentLen;//存放讀取檔案的二進位制流 try { Stream strm = reqFtp.GetRequestStream();//將FtpWebRequest轉換成stream型別 contentLen = stream.Read(buff, 0, buffLength);//存放讀取檔案的二進位制流 //進度條 while (contentLen != 0) { strm.Write(buff, 0, contentLen); contentLen = stream.Read(buff, 0, buffLength); } //釋放資源 stream.Close(); strm.Close(); erroinfo = "完成"; return true; } catch (Exception ex) { erroinfo = string.Format("無法完成上傳" + ex.Message); Debug.Log(erroinfo); return false; } } } }
呼叫:UpLoadFiles.UploadFiles("/config/", "test5.json"); config為FTP站點下資料夾名字

  

引用連結:https://blog.csdn.net/qq_42345116/article/details/111190763