从官网下载aws 的unity插件,并做了简单修改(主要用修改PostObject),问题:

(一)获取Pool ID

通过服务-Cognito-管理/新建用户池,可以新建或者获取Pool ID

(二)上传失败问题

使用unity插件中S3Example中PostObject时抛异常,但是获取GetObject没问题,此时需要在上传时代码中加一下区域,如下图所示。如果此时正在***,请暂停***,不允许通过代理访问(貌似是,本人报代理异常,改用VPN或者暂停***代理即可)

//----------------------------------------------代码--------------------------------------------------//

using UnityEngine;
using Amazon.S3;
using Amazon.S3.Model;
using Amazon.Runtime;
using System.IO;
using System;
using System.Collections.Generic;
using Amazon.CognitoIdentity;
using Amazon;public class AmazonS3Sdk : MonoBehaviour
{public string IdentityPoolId = "";public string CognitoIdentityRegion = RegionEndpoint.APSoutheast1.SystemName;private RegionEndpoint _CognitoIdentityRegion{get { return RegionEndpoint.GetBySystemName(CognitoIdentityRegion); }}public string S3Region = RegionEndpoint.APSoutheast1.SystemName;private RegionEndpoint _S3Region{get { return RegionEndpoint.GetBySystemName(S3Region); }}public string S3BucketName = null;public string SampleFileName = null;void Start(){UnityInitializer.AttachToGameObject(this.gameObject);AWSConfigs.HttpClient = AWSConfigs.HttpClientOption.UnityWebRequest;}#region private membersprivate IAmazonS3 _s3Client;private AWSCredentials _credentials;private AWSCredentials Credentials{get{if (_credentials == null)_credentials = new CognitoAWSCredentials(IdentityPoolId, _CognitoIdentityRegion);return _credentials;}}private IAmazonS3 Client{get{if (_s3Client == null){_s3Client = new AmazonS3Client(Credentials, _S3Region);}//test commentreturn _s3Client;}}#endregion#region Get Bucket List/// <summary>/// Example method to Demostrate GetBucketList/// </summary>public void GetBucketList(){Debug.Log("Fetching all the Buckets");Client.ListBucketsAsync(new ListBucketsRequest(), (responseObject) =>{Debug.Log(responseObject.Exception.ToString());if (responseObject.Exception == null){Debug.Log("Got Response");responseObject.Response.Buckets.ForEach((s3b) =>{string info = string.Format("bucket = {0}, created date = {1} \n", s3b.BucketName, s3b.CreationDate);Debug.Log(info);});}else{//ResultText.text += "Got Exception " + responseObject.Exception.ToString();Debug.Log("Fetching Buckets Exception:" + responseObject.Exception.ToString());}});}#endregion/// <summary>/// Get Object from S3 Bucket/// </summary>private void GetObject(){string info = string.Format("fetching {0} from bucket {1}", SampleFileName, S3BucketName);Debug.Log(info);Client.GetObjectAsync(S3BucketName, SampleFileName, (responseObj) =>{string data = null;var response = responseObj.Response;if (response.ResponseStream != null){using (StreamReader reader = new StreamReader(response.ResponseStream)){data = reader.ReadToEnd();}Debug.Log(data);//ResultText.text += data;
            }});}/// <summary>/// Post Object to S3 Bucket. /// </summary>public void PostObject(string file,string key,Action<string> action){Debug.Log("Posting the file");var stream = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read);//ResultText.text += "\nCreating request object";var request = new PostObjectRequest(){Bucket = S3BucketName,//Key = fileName,Key = key,InputStream = stream,CannedACL = S3CannedACL.Private,Region = _S3Region};Debug.Log("Making HTTP post call");Client.PostObjectAsync(request, (responseObj) =>{if (responseObj.Exception == null){string info = string.Format("\nobject {0} posted to bucket {1}", responseObj.Request.Key, responseObj.Request.Bucket);Debug.Log(info);if (action != null)action(responseObj.Request.Key);}else{Debug.Log("Posting Exception:"+ responseObj.Exception.ToString());//ResultText.text += string.Format("\n receieved error {0}", responseObj.Response.HttpStatusCode.ToString());
            }});}/// <summary>/// Get Objects from S3 Bucket/// </summary>public void GetObjects(){Debug.Log("Fetching all the Objects from " + S3BucketName);var request = new ListObjectsRequest(){BucketName = S3BucketName};Client.ListObjectsAsync(request, (responseObject) =>{//ResultText.text += "\n";if (responseObject.Exception == null){//ResultText.text += "Got Response \nPrinting now \n";responseObject.Response.S3Objects.ForEach((o) =>{string info = string.Format("{0}\n", o.Key);Debug.Log(info);});}else{string info = "Fetching Objects Exception:"+ responseObject.Exception.ToString();Debug.Log(info);}});}/// <summary>/// Delete Objects in S3 Bucket/// </summary>public void DeleteObject(){string info = string.Format("deleting {0} from bucket {1}", SampleFileName, S3BucketName);Debug.Log(info);List<KeyVersion> objects = new List<KeyVersion>();objects.Add(new KeyVersion(){Key = SampleFileName});var request = new DeleteObjectsRequest(){BucketName = S3BucketName,Objects = objects};Client.DeleteObjectsAsync(request, (responseObj) =>{//ResultText.text += "\n";if (responseObj.Exception == null){//ResultText.text += "Got Response \n \n";//ResultText.text += string.Format("deleted objects \n");
responseObj.Response.DeletedObjects.ForEach((dObj) =>{string str = dObj.Key;Debug.Log(str);});}else{string str = "Got Exception \n";Debug.Log(str);}});}private string GetFileHelper(){var fileName = SampleFileName;if (!File.Exists(Application.persistentDataPath + Path.DirectorySeparatorChar + fileName)){var streamReader = File.CreateText(Application.persistentDataPath + Path.DirectorySeparatorChar + fileName);streamReader.WriteLine("This is a sample s3 file uploaded from unity s3 sample");streamReader.Close();}return fileName;}private string GetPostPolicy(string bucketName, string key, string contentType){bucketName = bucketName.Trim();key = key.Trim();// uploadFileName cannot start with /if (!string.IsNullOrEmpty(key) && key[0] == '/'){throw new ArgumentException("uploadFileName cannot start with / ");}contentType = contentType.Trim();if (string.IsNullOrEmpty(bucketName)){throw new ArgumentException("bucketName cannot be null or empty. It's required to build post policy");}if (string.IsNullOrEmpty(key)){throw new ArgumentException("uploadFileName cannot be null or empty. It's required to build post policy");}if (string.IsNullOrEmpty(contentType)){throw new ArgumentException("contentType cannot be null or empty. It's required to build post policy");}string policyString = null;int position = key.LastIndexOf('/');if (position == -1){policyString = "{\"expiration\": \"" + DateTime.UtcNow.AddHours(24).ToString("yyyy-MM-ddTHH:mm:ssZ") + "\",\"conditions\": [{\"bucket\": \"" +bucketName + "\"},[\"starts-with\", \"$key\", \"" + "\"],{\"acl\": \"private\"},[\"eq\", \"$Content-Type\", " + "\"" + contentType + "\"" + "]]}";}else{policyString = "{\"expiration\": \"" + DateTime.UtcNow.AddHours(24).ToString("yyyy-MM-ddTHH:mm:ssZ") + "\",\"conditions\": [{\"bucket\": \"" +bucketName + "\"},[\"starts-with\", \"$key\", \"" + key.Substring(0, position) + "/\"],{\"acl\": \"private\"},[\"eq\", \"$Content-Type\", " + "\"" + contentType + "\"" + "]]}";}return policyString;}}

下面为.Net的上传物体可用代码

  //private static readonly string awsAccessKey = "*****************";//private static readonly string awsSecretKey = "***************************";private static readonly string awsAccessKey = "**********************************";private static readonly string awsSecretKey = "**************************";private static readonly string bucketName = "************";//private static readonly string bucketName = "****************";static AmazonS3Config config = new AmazonS3Config(){ServiceURL = "http://s3.amazonaws.com"};static AmazonS3Client client;//static AmazonS3Client amazonS3Client;static void Main(string[] args){//FileStream stream = File.OpenRead(args[0]);FileStream stream = File.OpenRead(@"D:\1107.jpg");//string resourcePath = @"D:\Demo\002.jpg";string info;//CreateBucket("test");//GetBucketList();//UploadbyPath(resourcePath);//Download(args[0]);using (AmazonS3Client amazonS3Client = new AmazonS3Client(awsAccessKey, awsSecretKey, config)){PutObjectRequest request = new PutObjectRequest(){BucketName = bucketName,//FilePath = args[0],InputStream = stream,CannedACL = S3CannedACL.PublicReadWrite,Key = Path.GetFileName("123")//ContentType = "text/plain"
                };try{amazonS3Client.PutObject(request);info = "success";//amazonS3Client.Dispose();
                }catch (AmazonS3Exception ex){info = "failed:" + ex.Message;}//TransferUtility transfer = new TransferUtility(amazonS3Client);//transfer.Upload(path, bucketName, Path.GetFileName(path));
            }//stream.Close();//stream.Dispose();//amazonS3Client.Dispose();//return args[0];
            Console.WriteLine(info);Console.ReadKey();}

转载于:https://www.cnblogs.com/llstart-new0201/p/9945540.html

Amazon S3数据存储相关推荐

  1. 【linux 上批量下载amazon s3数据】

    linux 上批量下载amazon s3数据 linux 上批量下载amazon s3数据 linux 上批量下载amazon s3数据 最近导师喊我下载amazon s3上的数据传到服务器上,没用过 ...

  2. Amazon S3文件存储的上传下载如何测试

    相信肯定有不少小伙伴的公司用到了S3,而且在测试的过程中如何去进行测试的呢,下面通过一篇文章带你入门S3的测试. S3是什么? Amazon Simple Storage Service (Amazo ...

  3. Amazon S3 云存储服务简介

    以下内容摘自IBM,完整原文链接:http://www.ibm.com/developerworks/cn/java/j-s3/ S3简介: 理论上,S3 是一个全球存储区域网络 (SAN),它表现为 ...

  4. 全方位保护您在 Amazon S3 的数据资产-访问控制详解

    2006年,Amazon S3 作为亚马逊云科技发布的第一款公有云服务面世,如今,成千上万的亚马逊云科技客户在利用 Amazon S3 创造各类激动人心的应用.从企业数据湖.机器学习存储,到 HPC. ...

  5. Amazon S3 Glacier 上线十周年,云端冷存储的十年

    点击上方入口立即[自由构建 探索无限] 一起共赴年度科技盛宴! 十年前,2012 年 8 月 20 日,亚马逊云科技宣布 Amazon Glacier 正式上市,这是一款安全.可靠.成本极低的存储设备 ...

  6. 使用Apache Hudi + Amazon S3 + Amazon EMR + AWS DMS构建数据湖

    1. 引入 数据湖使组织能够在更短的时间内利用多个源的数据,而不同角色用户可以以不同的方式协作和分析数据,从而实现更好.更快的决策.Amazon Simple Storage Service(amaz ...

  7. 基于 Bitbucket Pipeline + Amazon S3 的自动化运维体系

    1 前言介绍 随着自动化运维水平的提高,一个基础的运维人员维护成百上千台节点已经不是太难的事情,当然,这需要依靠于稳定.高效的自动化运维体系.本篇文章即是阐述如何利用 bitbucket pipeli ...

  8. minio 并发数_开源数据存储项目Minio:提供非结构化数据储存服务

    Minio是一个在Apache Licence 2.0下发布的对象存储服务器.官网:https://minio.io.它与Amazon S3云存储服务兼容.Minio最适合存储非结构化数据,如照片.视 ...

  9. amazon s3_在Amazon S3上托管静态网站

    amazon s3 Static website hosting on Amazon S3 is one of the very popular use cases of Amazon S3. It ...

最新文章

  1. 基于Matlab的多层BP神经网络在非线性函数拟合中的应用
  2. JavaScript标准库系列——RegExp对象(三)
  3. ubi-partman failed with exit code 141
  4. 1027:输出浮点数
  5. 最简单的基于librtmp的示例:发布H.264(H.264通过RTMP发布)
  6. 机器学习解决问题思路 — 词嵌入矩阵E对于NLP问题的重要性
  7. 四种有能力取代Cookies的客户端Web存储方案
  8. python自动化办公-简直出神入化,教你用Python控制Excel实现自动化办公
  9. nginx的虚拟用户以及负载均衡
  10. excel显著性检验_数据分析系列 10/32 | Excel方差分析之单因素方差分析
  11. cad画正弦曲线lisp_cadlisp基础教程.pdf
  12. R语言绘图基础篇-线图
  13. matlab一键计算平均值与标准偏差
  14. ddos硬件防火墙(DDOS硬件防火墙)
  15. SP商BI平台(MP子平台)——通信增值业务运营SP公司
  16. 大学计算机与人工智能基础课后答案,好书推荐 | 人工智能基础及应用
  17. 怎样设置一个函数C语言,C语言中怎样编写一个函数 如何在C语言中定义一个函数?...
  18. linux指令_周东海
  19. 忆二十几年前的“大案”|我们该教什么给孩子?
  20. python常用的数字类型方法_python基础--数据类型的常用方法1

热门文章

  1. 12c:CREATE DATABASE——DBCA
  2. java处理excel(java使用Apache POI处理Excel)
  3. HTML中引入CSS的方法
  4. 什么是Low Code ? 居然能威胁到专业程序员?
  5. 写给老宅程序员的一些建议
  6. 记一次悲惨的 Excel 导出事件
  7. Java集合:数组的使用
  8. Android --- 199 198开头手机号正则表达式无效
  9. Android --- log.e(),log.d(),log.i()等的区别
  10. 服务器光信号闪红灯是什么意思,路由器光信号闪红灯是什么意思