Unityから直接FTP接続でアップロードするサンプルソースです。
FC2無料サーバーで動作確認をしました。
プロジェクト直下のindexファイルをサーバー直下にアップロードします。
using UnityEngine;
using System;
using System.IO;
using System.Net;
public class FTPUP : MonoBehaviour
{
private string host = null;
private string user = null;
private string pass = null;
private FtpWebRequest ftpRequest = null;
private Stream ftpStream = null;
private const int bufferSize = 2048;
public FTPUP(string hostIP, string userName, string password) { host = hostIP; user = userName; pass = password; }
public void Upload(string remote_file, string local_file)
{
try
{
/* Create an FTP Request */
ftpRequest = (FtpWebRequest)FtpWebRequest.Create(host + "/" + remote_file);
ftpRequest.Credentials = new NetworkCredential(user, pass);
ftpRequest.UseBinary = true;
ftpRequest.UsePassive = true;
ftpRequest.KeepAlive = true;
ftpRequest.Method = WebRequestMethods.Ftp.UploadFile;
ftpStream = ftpRequest.GetRequestStream();
FileStream localFileStream = new FileStream(local_file, FileMode.Open);
byte[] byteBuffer = new byte[bufferSize];
int bytesSent = localFileStream.Read(byteBuffer, 0, bufferSize);
try
{
while (bytesSent != 0)
{
ftpStream.Write(byteBuffer, 0, bytesSent);
bytesSent = localFileStream.Read(byteBuffer, 0, bufferSize);
}
}
catch (Exception ex)
{
Debug.Log(ex.ToString()+"UP1");
}
/* Resource Cleanup */
localFileStream.Close();
ftpStream.Close();
ftpRequest = null;
}
catch (Exception ex)
{
Debug.Log(ex.ToString()+"Up2");
}
return;
}
public void TestUP(){
//FTPUP ftp = new FTPUP(FTPURL, UserName, FTPPass);
FTPUP ftp = new FTPUP(@"ftp://XXXXX.web.fc2.com", @"ユーザ名", @"パスワード");
string stCurrentDir = System.IO.Directory.GetCurrentDirectory();
Debug.Log (stCurrentDir);
string filename = System.IO.Path.GetFileName(stCurrentDir +@"/index.html" );
ftp.Upload(@"/index.html", filename);
ftp = null;
}
}
0 件のコメント:
コメントを投稿