完整教程:unity WebGL平台往阿里云OSS上传txt文件 以及上传图片(不能通过Win对话框选择本地图片)

unity 网页OSS上传

不知道怎么获取阿里云的key的,请看这个文章

第一步 在unity中创建Plugins文件夹,并创建一个OSSWrapper.jslib文件,然后用文本打开,把下面的代码粘贴到里面

在这里插入图片描述

mergeInto(LibraryManager.library, {
OSS_Init: function (accessKeyId, accessKeySecret, endpoint, bucketName) {
var ak = UTF8ToString(accessKeyId);
var aks = UTF8ToString(accessKeySecret);
var ep = UTF8ToString(endpoint);
var bn = UTF8ToString(bucketName);
ep = ep.replace('https://', '').replace('http://', '');
console.log("OSSpeiz:", { endpoint: ep, bucket: bn });
window.OSSConfig = {
accessKeyId: ak,
accessKeySecret: aks,
endpoint: ep,
bucket: bn,
secure: true
};
},
OSS_UploadText: function (objectKey, content, callbackName) {
var key = UTF8ToString(objectKey);
var text = UTF8ToString(content);
var cb = UTF8ToString(callbackName);
setTimeout(function() {
try {
if (typeof window.OSS === 'undefined') {
SendMessage('OSSManager', cb, 'error:OSS SDK not loaded');
return;
}
if (!window.OSSConfig) {
SendMessage('OSSManager', cb, 'error:OSS not initialized');
return;
}
console.log("OSS:", window.OSSConfig);
var client = new window.OSS({
accessKeyId: window.OSSConfig.accessKeyId,
accessKeySecret: window.OSSConfig.accessKeySecret,
endpoint: window.OSSConfig.endpoint,
bucket: window.OSSConfig.bucket,
secure: true
});
console.log("shangchuan:", key);
var blob = new Blob([text], { type: 'text/plain' });
client.put(key, blob).then(function(result) {
console.log("shuangchuanchengchenggong", result);
SendMessage('OSSManager', cb, 'success');
}).catch(function(err) {
console.error("error:", err);
console.error("zhuangtai:", err.status);
console.error("code:", err.code);
SendMessage('OSSManager', cb, 'error:' + err.message + '|code:' + (err.code || 'unknown'));
});
} catch (e) {
console.error("22222:", e);
SendMessage('OSSManager', cb, 'error:' + e.message);
}
}, 100);
},
OSS_UploadImage: function (objectKey, imageDataPtr, dataLength, mimeType, callbackName) {
var key = UTF8ToString(objectKey);
var mime = UTF8ToString(mimeType);
var cb = UTF8ToString(callbackName);
var data = new Uint8Array(HEAPU8.buffer, imageDataPtr, dataLength);
var dataCopy = new Uint8Array(data);
setTimeout(function() {
try {
if (typeof window.OSS === 'undefined') {
SendMessage('OSSManager', cb, 'error:OSS SDK not loaded');
return;
}
if (!window.OSSConfig) {
SendMessage('OSSManager', cb, 'error:OSS not initialized');
return;
}
var client = new window.OSS({
accessKeyId: window.OSSConfig.accessKeyId,
accessKeySecret: window.OSSConfig.accessKeySecret,
endpoint: window.OSSConfig.endpoint,
bucket: window.OSSConfig.bucket,
secure: true
});
var blob = new Blob([dataCopy], { type: mime });
client.put(key, blob).then(function(result) {
SendMessage('OSSManager', cb, 'success');
}).catch(function(err) {
SendMessage('OSSManager', cb, 'error:' + err.message + '|code:' + (err.code || 'unknown'));
});
} catch (e) {
SendMessage('OSSManager', cb, 'error:' + e.message);
}
}, 100);
}
});

第二步创建Unity代码,一共两个脚本WebGLOSS和OSSUI

using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using UnityEngine;
using UnityEngine.Networking;
public class WebGLOSS : MonoBehaviour
{
[DllImport("__Internal")]
private static extern void OSS_Init(string accessKeyId, string accessKeySecret, string endpoint, string bucketName);
[DllImport("__Internal")]
private static extern void OSS_UploadText(string objectKey, string content, string callbackName);
[DllImport("__Internal")]
private static extern void OSS_UploadImage(string objectKey, byte[] imageData, int dataLength, string mimeType, string callback);
[Header("OSS配置")]
public const string AccessKeyId = "自己的AccessKeyId ";
public const string AccessKeySecret = "自己的AccessKeySecret";
public const string EndPoint = "https://oss-cn-beijing.aliyuncs.com";//我都是北京的所以是这个,其他地区的,看下图找到自己地区的访问端口
public const string Bucket = "自己的桶的名字";
private Action<bool, string> currentCallback;
  void Start()
  {
  InitializeOSS();
  }
  public void InitializeOSS()
  {
  #if UNITY_WEBGL && !UNITY_EDITOR
  OSS_Init(AccessKeyId, AccessKeySecret, EndPoint, Bucket);
  #endif
  }
  public void CreateTextFile(string objectKey, string content, Action<bool, string> callback = null)
    {
    currentCallback = callback;
    #if UNITY_WEBGL && !UNITY_EDITOR
    OSS_UploadText(objectKey, content, "OnOSSUploadResult");
    #else
    Debug.Log($"模拟上传: {objectKey}\n内容: {content}");
    OnOSSUploadResult("success");
    #endif
    }
    public void UploadImage(string objectKey, byte[] imageData, int dataLength, string mimeType, Action<bool, string> callback = null)
      {
      currentCallback = callback;
      #if UNITY_WEBGL && !UNITY_EDITOR
      OSS_UploadImage(objectKey, imageData, dataLength, mimeType, "OnOSSUploadResult");
      #else
      Debug.Log($"模拟上传: {objectKey}\n内容: {imageData}");
      OnOSSUploadResult("success");
      #endif
      }
      // 被JavaScript调用的回调方法
      public void OnOSSUploadResult(string result)
      {
      bool success = result == "success";
      string message = success ? "上传成功" : result;
      Debug.Log($"OSS上传结果: {message}");
      currentCallback?.Invoke(success, message);
      currentCallback = null;
      }
      }

在这里插入图片描述

using System;
using System.Collections;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;
public class OSSUI : MonoBehaviour
{
public WebGLOSS ossManager;
public InputField fileNameInput;
public InputField contentInput;
public Button uploadButton;
void Start()
{
uploadButton.onClick.AddListener(CreateTextFileOnOSS);
}
void CreateTextFileOnOSS()
{
string fileName = string.IsNullOrEmpty(fileNameInput.text) ?
$"file_{System.DateTime.Now:yyyyMMddHHmmss}.txt" : fileNameInput.text + ".txt";
string content = string.IsNullOrEmpty(contentInput.text) ?
"" : contentInput.text;
ossManager.CreateTextFile(fileName, content, (success, message) =>
{
if (success)
{
Debug.Log("文件创建成功!");
}
else
{
Debug.LogError("创建失败: " + message);
}
});
}
void CreateTextFileOnOSSPNG2()
{
// 图片文件名
string imageName = "图片.png";
// 构建图片路径
string imagePath = System.IO.Path.Combine(Application.streamingAssetsPath, imageName);
// 加载图片
StartCoroutine(LoadAndUploadImage2(imagePath));
}
private IEnumerator LoadAndUploadImage2(string imagePath)
{
// 使用 UnityWebRequestTexture 加载图片
using (UnityWebRequest www = UnityWebRequestTexture.GetTexture(imagePath))
{
yield return www.SendWebRequest();
if (www.result != UnityWebRequest.Result.Success)
{
Debug.LogError($"加载图片失败: {www.error}");
yield break;
}
// 获取Texture2D对象
Texture2D texture = DownloadHandlerTexture.GetContent(www);
byte[] imageData = texture.EncodeToPNG();
// 上传Texture2D
ossManager.UploadImage("test.png", imageData, imageData.Length, "image/png", (success, message) =>
{
if (success)
{
Debug.Log("图片上传成功!");
}
else
{
Debug.LogError("图片上传失败: " + message);
}
});
}
}
}

在这里插入图片描述

第三步 创建index模版,写入oss的js的SDK,然后打包选着自定义的index模版,打包就可以

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述
要选着不压缩,
在这里插入图片描述

posted @ 2025-10-23 21:00  ycfenxi  阅读(3)  评论(0)    收藏  举报