从官网下载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数据存储的更多相关文章

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

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

  2. Amazon Redshift数据迁移到MaxCompute

    Amazon Redshift数据迁移到MaxCompute Amazon Redshift 中的数据迁移到MaxCompute中经常需要先卸载到S3中,再到阿里云对象存储OSS中,大数据计算服务Ma ...

  3. 详解Amazon S3上传/下载数据

    AWS简单储存服务(Amazon S3)是非常坚牢的存储服务,拥有99.999999999%的耐久性(记住11个9的耐久性). 使用CloudBerry Explorer,从Amazon S3下载数据 ...

  4. Hive中导入Amazon S3中的分区表数据的操作

    Hive中创建S3的外部表 数据在S3存放的数据是按时间纬度存放的,每天的数据存放在各自的目录下,目录结构如下截图: 每个目录下面的数据是CSV文件,现在将其导入到Hive中进行查询,通过创建对应的表 ...

  5. Amazon S3 API

    一.概述 Amazon s3,全称为Amazon Simple Storage  Service.EC2和S3是Amazon最早推出的两项云服务. REST,这也是比较火的一种Web服务架构.简单来说 ...

  6. Amazon S3 功能介绍

    一 .Amazon S3介绍 Amazon Simple Storage Service (Amazon S3) 是一种对象存储,它具有简单的 Web 服务接口,可用于在 Web 上的任何位置存储和检 ...

  7. HBase介绍(2)---数据存储结构

    在本文中的HBase术语:基于列:column-oriented行:row列组:column families列:column单元:cell 理解HBase(一个开源的Google的BigTable实 ...

  8. Amazon S3 云服务

    一.简介 Amazon Simple Storage Service (S3) 是一个公开的服务,Web 应用程序开发人员可以使用它存储数字资产,包括图片.视频.音乐和文档. S3 提供一个 REST ...

  9. asp.net core系列 69 Amazon S3 资源文件上传示例

    一.  上传示例 Install-Package AWSSDK.S3 -Version 3.3.104.10 using Amazon; using Amazon.Runtime; using Ama ...

随机推荐

  1. selenium-03-常用操作

    基本介绍: Selenium工具专门为WEB应用程序编写的一个验收测试工具. Selenium的核心:browser bot,是用JavaScript编写的. Selenium工具有4种:Seleni ...

  2. Java 基础篇之类与对象

    类与对象 类.对象和引用的关系 类和对象的关系 类是对象的模版,对象是类的一个实例,一个类可以有很多对象 一个Java程序中类名相同的类只能有一个,也就是类型不会重名 一个对象只能根据一个类来创建 引 ...

  3. rpm -qa|grep nfs >/dev/null 2>&1作用

    在使用一些shell命令是,经常会用到rpm -qa|grep nfs >/dev/null 2>&1之类的命令,该命令干嘛用的呢? 其实这个命令就是将rpm -qa|grep n ...

  4. logrotate 不生效

    登录服务器查看,发现日志没有自动切割.去查看micros配置文件: [root@ecs-11-151 ~]# cat /etc/logrotate.d/micros /data/logs/*/*.lo ...

  5. JS多线程WebWorker

    JS多线程WebWorker 一,介绍与需求 1.1,介绍 Web Worker可以为JavaScript创建多线程,且Web Worker 是运行在后台的 JavaScript,独立于其他脚本,不会 ...

  6. 前端深入之css篇|你真的了解“权重”吗?

    写在前面 权重这个概念,相信对许多进行过前端开发的小伙伴来说肯定并不陌生,有时候一个样式添加不上,我们就会一个 !important 怼上去,一切就好像迎刃而解了.但还有的时候,!important也 ...

  7. Dockerfile 构建镜像

    一.使用dockerfile构建镜像 基本结构: a.设置基础镜像 当前镜像继承于的基础镜像 FROM centos:latest  b.设置维护者信息 没有固定格式  c.设置需要添加到容器中的文件 ...

  8. svg foreignObject的作用(文本换行,生成图片)

    SVG内部利用foreignObject嵌入XHTML元素 <foreignObject>元素的作用是可以在其中使用具有其它XML命名空间的XML元素,换句话说借助<foreignO ...

  9. electron教程(四): 使用electron-builder或electron-packager将项目打包为可执行桌面程序(.exe)

    我的electron教程系列 electron教程(一): electron的安装和项目的创建 electron教程(二): http服务器, ws服务器, 子进程管理 electron教程(三): ...

  10. Js获取宽高度的归纳集锦总结

    首先,先吓唬一下我们的小白们!在js中的描述宽高的可以细分有22种.属性根据不同的兼容性也分为五种 window.innerWidth //除去菜单栏的窗口宽度,与浏览器相关 window.inner ...