转载自 Shirlman 的 Unity通过RestSharp调用阿里云OSS REST API
Unity上用阿里云的oss服务,网上资料并不多,而且官方没有给出Unity的SDK,因此只能用REST API来实现了。
调研oss在unity上的可行性的话,开始总得跑个demo看看行不行的通,这里以上传图片为例子,可以先看看官方的文档。
从文档中发现,需要自己实现签名,另外header中的信息和签名中的加密信息必须一致,比如时间和MD5值,如果签名算法有问题,阿里云就会返回相应的错误提示。
我自己封装了个简单的例子,有需要的可以参考下,在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;
}
}
调用方式:
OssManager.GetInstance().UploadFileAsync("C:/Pictures/oss.jpg", "Images");
运行结果: