Amazon S3数据存储
从官网下载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 members private 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 comment
return _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[] == '/')
{
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 == -)
{
policyString = "{\"expiration\": \"" + DateTime.UtcNow.AddHours().ToString("yyyy-MM-ddTHH:mm:ssZ") + "\",\"conditions\": [{\"bucket\": \"" +
bucketName + "\"},[\"starts-with\", \"$key\", \"" + "\"],{\"acl\": \"private\"},[\"eq\", \"$Content-Type\", " + "\"" + contentType + "\"" + "]]}";
}
else
{
policyString = "{\"expiration\": \"" + DateTime.UtcNow.AddHours().ToString("yyyy-MM-ddTHH:mm:ssZ") + "\",\"conditions\": [{\"bucket\": \"" +
bucketName + "\"},[\"starts-with\", \"$key\", \"" + key.Substring(, 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("")
//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();
}
Amazon S3数据存储的更多相关文章
- 使用Apache Hudi + Amazon S3 + Amazon EMR + AWS DMS构建数据湖
1. 引入 数据湖使组织能够在更短的时间内利用多个源的数据,而不同角色用户可以以不同的方式协作和分析数据,从而实现更好.更快的决策.Amazon Simple Storage Service(amaz ...
- Amazon Redshift数据迁移到MaxCompute
Amazon Redshift数据迁移到MaxCompute Amazon Redshift 中的数据迁移到MaxCompute中经常需要先卸载到S3中,再到阿里云对象存储OSS中,大数据计算服务Ma ...
- 详解Amazon S3上传/下载数据
AWS简单储存服务(Amazon S3)是非常坚牢的存储服务,拥有99.999999999%的耐久性(记住11个9的耐久性). 使用CloudBerry Explorer,从Amazon S3下载数据 ...
- Hive中导入Amazon S3中的分区表数据的操作
Hive中创建S3的外部表 数据在S3存放的数据是按时间纬度存放的,每天的数据存放在各自的目录下,目录结构如下截图: 每个目录下面的数据是CSV文件,现在将其导入到Hive中进行查询,通过创建对应的表 ...
- Amazon S3 API
一.概述 Amazon s3,全称为Amazon Simple Storage Service.EC2和S3是Amazon最早推出的两项云服务. REST,这也是比较火的一种Web服务架构.简单来说 ...
- Amazon S3 功能介绍
一 .Amazon S3介绍 Amazon Simple Storage Service (Amazon S3) 是一种对象存储,它具有简单的 Web 服务接口,可用于在 Web 上的任何位置存储和检 ...
- HBase介绍(2)---数据存储结构
在本文中的HBase术语:基于列:column-oriented行:row列组:column families列:column单元:cell 理解HBase(一个开源的Google的BigTable实 ...
- Amazon S3 云服务
一.简介 Amazon Simple Storage Service (S3) 是一个公开的服务,Web 应用程序开发人员可以使用它存储数字资产,包括图片.视频.音乐和文档. S3 提供一个 REST ...
- asp.net core系列 69 Amazon S3 资源文件上传示例
一. 上传示例 Install-Package AWSSDK.S3 -Version 3.3.104.10 using Amazon; using Amazon.Runtime; using Ama ...
随机推荐
- 【Django】ModelForm
ModelForm 1.Model与Form内容回顾 Model - 数据库操作 - 验证 class A(MOdel): user = email = pwd = Form - class Logi ...
- JAVA线程通信之生产者与消费者
package cn.test.hf.test3; import java.util.concurrent.locks.Condition;import java.util.concurrent.lo ...
- Spring框架学习笔记(3)——SpringMVC框架
SpringMVC框架是基于Spring框架,可以让我们更为方便的进行Web的开发,实现前后端分离 思路和原理 我们之前仿照SpringMVC定义了一个自定义MVC框架,两者的思路其实都是一样的. 建 ...
- 百万it资源百度网盘链接分享
自己大量时间整理的优质资源,容量达3000多G,有需要的朋友可以微我,资源截图: 面试资料: 书籍类: 视频类: 以上只是部分资源,想要资源的亲请加微信咨询. 欢迎加微信咨询,请备注资源: 独乐乐不 ...
- 证明xcosx无周期
假设\(xcos\,x\)有周期,依据周期函数的规律,可得 \[ \begin{aligned} xcos\,x & = (x+T)cos\,(x+T) \\ & = (x+T)cos ...
- yii2 qq邮箱配置发送
'mailer' => [ 'class' => 'yii\swiftmailer\Mailer', 'useFileTransport' =>false,//这句一定有,false ...
- js中对于数组的操作
let myArray=[11,22,33]; console.log('原数组:',myArray); myArray.push(44,55); console.log('用push在数组后面插入元 ...
- python 3.7 使用MP3play 模块
因工作需要,做了一个QQ机器人语音播报程序.主要思路 是通过 酷Q 获取QQ消息取出有效信息. 根据信息在百度AI上合成语音,然后本地播放. 在播放语音的时候用了好几个模块 pygame .pyme ...
- reduce方法应用技巧
定义和用法 reduce() 方法接收一个函数作为累加器,数组中的每个值(从左到右)开始缩减,最终计算为一个值. 注意: reduce() 对于空数组是不会执行回调函数的. 浏览器支持 方法 Chro ...
- C# 8 的模式匹配
C# 7 里面的Pattern Mathing is 模式 switch 和 when C# 8 里面的Pattern Matching 使用Deconstructor 和 位置匹配模式 下面两个类T ...