轉(zhuǎn)載自 Shirlman 的 Unity通過RestSharp調(diào)用阿里云OSS REST API
Unity上用阿里云的oss服務(wù)殖演,網(wǎng)上資料并不多猾漫,而且官方?jīng)]有給出Unity的SDK,因此只能用REST API來實現(xiàn)了霍掺。
調(diào)研oss在unity上的可行性的話匾荆,開始總得跑個demo看看行不行的通,這里以上傳圖片為例子杆烁,可以先看看官方的文檔牙丽。
從文檔中發(fā)現(xiàn),需要自己實現(xiàn)簽名兔魂,另外header中的信息和簽名中的加密信息必須一致烤芦,比如時間和MD5值,如果簽名算法有問題析校,阿里云就會返回相應(yīng)的錯誤提示构罗。
我自己封裝了個簡單的例子,有需要的可以參考下智玻,在windows和android上測試通過遂唧,另外我用的是Unity5.4版本,RestSharp可以在文章最后下載吊奢,不知道什么版本盖彭,15年12月份的。
ps:為什么要用RestSharp?www不支持PUT召边,然后HttpWebRequest沒試通铺呵,偷懶用RestSharp了,最近貌似都不更新了隧熙,但是用著感覺還行吧~
完整代碼如下:
using UnityEngine;
using System.Collections;
using System.Security.Cryptography;
using System.Text;
using System;
using System.IO;
using RestSharp;
public class OssManager : MonoBehaviour {
private const string OSS_HOST = "vrhouse.oss-cn-shanghai.aliyuncs.com";
private const string BUCKET_NAME = "your_bucket_name";
private const string ACCESS_KEY_ID = "your_access_key_id";
private const string ACCESS_KEY_SECRET = "your_access_key_secret";
private static OssManager mInstance;
void Awake()
{
mInstance = this;
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
public static OssManager GetInstance()
{
return mInstance;
}
/// <summary>
///
/// </summary>
/// <param name="imagePath">本地文件絕對路徑</param>
/// <param name="bucketPath">需要保存的文件在bucket上的相對路徑片挂,前后不需要加'/',也不需要加文件名</param>
public void UploadFileAsync(string imagePath, string bucketPath)
{
StartCoroutine(UploadImage(imagePath, bucketPath));
}
IEnumerator UploadImage(string imagePath, string bucketPath)
{
WWW loadedImage = new WWW("file:///" + imagePath);
yield return loadedImage;
string fileName = Path.GetFileName(imagePath);
string bucketFilePath = "/" + bucketPath + "/" + fileName;
string url = "http://" + OSS_HOST + bucketFilePath;
string contentMD5 = ToMD5(imagePath);
string contentType = "image/" + Path.GetExtension(imagePath).Remove(0, 1);
string utcGMT = DateTime.UtcNow.ToString("r");
string canonicalizedOSSHeaders = "";
string canonicalizedResource = "/" + BUCKET_NAME + "/" + fileName;
string authorization = GetAuthorization("PUT", contentMD5, contentType, utcGMT, canonicalizedOSSHeaders, canonicalizedResource);
var client = new RestClient(url);
var request = new RestRequest(Method.PUT);
// Headers
request.AddHeader("Content-Encoding", "utf-8");
request.AddHeader("Content-Md5", contentMD5);
request.AddHeader("Content-Disposition", "attachment;filename=" + fileName);
request.AddHeader("Date", utcGMT);
request.AddHeader("Content-Length", loadedImage.bytes.Length.ToString());
request.AddHeader("Host", OSS_HOST);
request.AddHeader("Authorization", "'" + authorization + "'"); // 這里一定要加引號
// 這里需要這么處理贞盯,如果用AddFile宴卖,RestSharp會加multipart類型的content type,保存到OSS上的圖片會無法查看
request.AddParameter(contentType, loadedImage.bytes, ParameterType.RequestBody);
// execute the request
IRestResponse response = client.Execute(request);
var content = response.Content; // raw content as string
Debug.Log(content);
}
private string GetAuthorization(
string method, string contentMD5, string contentType,
string utcGMT, string canonicalizedOSSHeaders, string canonicalizedResource)
{
string data = method + "\n"
+ contentMD5 + "\n"
+ contentType + "\n"
+ utcGMT + "\n"
+ canonicalizedOSSHeaders
+ canonicalizedResource;
string signature = ToHMACSHA1_Base64(ACCESS_KEY_SECRET, data);
string authorization = "OSS " + ACCESS_KEY_ID + ":" + signature;
return authorization;
}
private string ToHMACSHA1_Base64(string key, string data)
{
HMACSHA1 hmacsha1 = new HMACSHA1();
hmacsha1.Key = Encoding.UTF8.GetBytes(key);
byte[] dataBuffer = Encoding.UTF8.GetBytes(data);
byte[] hashBytes = hmacsha1.ComputeHash(dataBuffer);
string result = Convert.ToBase64String(hashBytes);
return result;
}
private string ToMD5(string filePath)
{
FileStream file = new FileStream(filePath, FileMode.Open);
MD5 md5 = new MD5CryptoServiceProvider();
byte[] hashBytes = md5.ComputeHash(file);
file.Close();
string result = Convert.ToBase64String(hashBytes);
return result;
}
}
調(diào)用方式:
OssManager.GetInstance().UploadFileAsync("C:/Pictures/oss.jpg", "Images");
運行結(jié)果:
運行結(jié)果