public void UploadToS3(string path, string fileName) { FileStream stream = new FileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite); PostObjectRequest request = new PostObjectRequest() { Bucket = "serviceappcasefiles123", Key = "case#" + fileName, InputStream = stream, CannedACL = S3CannedACL.Private, Region = _S3Region }; S3Client.PostObjectAsync(request, (responseObject) => { if (responseObject.Exception == null) { Debug.Log("posted to bucket."); SceneManager.LoadScene(0); UIManager.Instance.couter = 0; UIManager.Instance.listObjects.Clear(); } else { Debug.Log("Execption occured" + responseObject.Exception); } }); }
/// <summary> /// Post Object to S3 Bucket. /// </summary> public void UploadObjectForBucket(string pathFile, string S3BucketName, string fileNameOnBucket, Action <PostObjectResponse, string> result) { if (!File.Exists(pathFile)) { result?.Invoke(null, "FileNotFoundException: Could not find file " + pathFile); return; } var stream = new FileStream(pathFile, FileMode.Open, FileAccess.Read, FileShare.Read); var request = new PostObjectRequest() { Bucket = S3BucketName, Key = fileNameOnBucket, InputStream = stream, CannedACL = S3CannedACL.Private, Region = S3Region }; Client.PostObjectAsync(request, (responseObj) => { if (responseObj.Exception == null) { result?.Invoke(responseObj.Response, ""); } else { result?.Invoke(null, responseObj.Exception.ToString()); } }); }
/// <summary> /// Post Object to S3 Bucket. /// </summary> public PostObjectRequest PostObject(string filePath, string s3FolderName, Action <string> onSuccess = null) { string fileName = s3FolderName + "/" + System.IO.Path.GetFileName(filePath); VRC.Core.Logger.Log("uploading " + fileName, VRC.Core.DebugLevel.All); AWSConfigs.LoggingConfig.LogTo = LoggingOptions.None; var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read); VRC.Core.Logger.Log("Creating request object", VRC.Core.DebugLevel.All); var request = new PostObjectRequest() { Bucket = S3BucketName, Key = fileName, InputStream = stream, CannedACL = S3CannedACL.Private }; VRC.Core.Logger.Log("Making HTTP post call", VRC.Core.DebugLevel.All); StartCoroutine(PostObjectRoutine(request, onSuccess)); return(request); }
private void CreateSignedPolicy(PostObjectRequest request) { if (request.ContentType == null) { int pos = request.Key.LastIndexOf('.'); string ext = null; if (pos != -1) { ext = request.Key.Substring(pos, request.Key.Length - pos); request.ContentType = AmazonS3Util.MimeTypeFromExtension(ext); } else { request.ContentType = "application/octet-stream"; } } string policyString = null; int position = request.Key.LastIndexOf('/'); if (position == -1) { policyString = "{\"expiration\": \"" + DateTime.UtcNow.AddHours(24).ToString("yyyy-MM-ddTHH:mm:ssZ") + "\",\"conditions\": [{\"bucket\": \"" + request.Bucket + "\"},[\"starts-with\", \"$key\", \"" + "\"],{\"acl\": \"private\"},[\"eq\", \"$Content-Type\", " + "\"" + request.ContentType + "\"" + "]]}"; } else { policyString = "{\"expiration\": \"" + DateTime.UtcNow.AddHours(24).ToString("yyyy-MM-ddTHH:mm:ssZ") + "\",\"conditions\": [{\"bucket\": \"" + request.Bucket + "\"},[\"starts-with\", \"$key\", \"" + request.Key.Substring(0, position) + "/\"],{\"acl\": \"private\"},[\"eq\", \"$Content-Type\", " + "\"" + request.ContentType + "\"" + "]]}"; } request.SignedPolicy = S3PostUploadSignedPolicy.GetSignedPolicy(policyString, base.Credentials); }
public static void AsynPostObject(COSXML.CosXml cosXml, string bucket, string key, string srcPath, PostObjectRequest.Policy policy) { PostObjectRequest request = new PostObjectRequest(bucket, key, srcPath); //设置签名有效时长 request.SetSign(TimeUtils.GetCurrentTime(TimeUnit.SECONDS), 600); request.SetCosProgressCallback(delegate(long completed, long total) { Console.WriteLine(String.Format("progress = {0} / {1} : {2:##.##}%", completed, total, completed * 100.0 / total)); }); //设置policy request.SetPolicy(policy); //执行请求 cosXml.PostObject(request, delegate(CosResult result) { PostObjectResult getObjectResult = result as PostObjectResult; Console.WriteLine(getObjectResult.GetResultInfo()); }, delegate(CosClientException clientEx, CosServerException serverEx) { if (clientEx != null) { QLog.D("XIAO", clientEx.Message); Console.WriteLine("CosClientException: " + clientEx.StackTrace); } if (serverEx != null) { QLog.D("XIAO", serverEx.Message); Console.WriteLine("CosServerException: " + serverEx.GetInfo()); } }); }
IEnumerator PostObjectRoutine(PostObjectRequest request, Action <string> onSuccess) { // make sure UnityInitializer call has time to initialize yield return(null); yield return(null); Client.PostObjectAsync(request, (responseObj) => { if (responseObj.Exception == null) { VRC.Core.Logger.Log("object " + responseObj.Request.Key + " posted to bucket " + responseObj.Request.Bucket, VRC.Core.DebugLevel.All); string s3Url = string.Format("https://s3-us-west-2.amazonaws.com/{0}/{1}", responseObj.Request.Bucket, responseObj.Request.Key); if (onSuccess != null) { onSuccess(s3Url); } } else { VRC.Core.Logger.Log("Exception while posting the result object"); VRC.Core.Logger.Log("receieved error " + responseObj.Response.HttpStatusCode.ToString()); } }); }
public void testPostObjectTrafficLimit() { try { long now = new DateTimeOffset(DateTime.UtcNow).ToUnixTimeMilliseconds(); PostObjectRequest request = new PostObjectRequest(bucket, commonKey, smallFileSrcPath); request.LimitTraffic(8 * 1000 * 1024); //执行请求 PostObjectResult result = cosXml.PostObject(request); long costTime = new DateTimeOffset(DateTime.UtcNow).ToUnixTimeMilliseconds() - now; Console.WriteLine("costTime = " + costTime + "ms"); Console.WriteLine(result.GetResultInfo()); Assert.True(result.httpCode == 204); // Assert.True(costTime > 8000 && costTime < 14000); } catch (COSXML.CosException.CosClientException clientEx) { Console.WriteLine("CosClientException: " + clientEx.Message); Assert.True(false); } catch (COSXML.CosException.CosServerException serverEx) { Console.WriteLine("CosServerException: " + serverEx.GetInfo()); Assert.True(false); } }
public static void PostObject(COSXML.CosXml cosXml, string bucket, string key, string srcPath, PostObjectRequest.Policy policy) { try { PostObjectRequest request = new PostObjectRequest(bucket, key, srcPath); //设置签名有效时长 //request.SetSign(TimeUtils.GetCurrentTime(TimeUnit.SECONDS), 600); List <string> headers = new List <string>(); headers.Add("Host"); request.SetSign(TimeUtils.GetCurrentTime(TimeUnit.SECONDS), 600, headers, null); request.SetCosProgressCallback(delegate(long completed, long total) { Console.WriteLine(String.Format("progress = {0} / {1} : {2:##.##}%", completed, total, completed * 100.0 / total)); }); //设置policy request.SetPolicy(policy); //执行请求 PostObjectResult result = cosXml.PostObject(request); Console.WriteLine(result.GetResultInfo()); } catch (COSXML.CosException.CosClientException clientEx) { QLog.D("XIAO", clientEx.Message); Console.WriteLine("CosClientException: " + clientEx.StackTrace); } catch (COSXML.CosException.CosServerException serverEx) { QLog.D("XIAO", serverEx.Message); Console.WriteLine("CosServerException: " + serverEx.GetInfo()); } }
// Token: 0x060063F6 RID: 25590 RVA: 0x002378AC File Offset: 0x00235CAC private IEnumerator PostObjectRoutine(PostObjectRequest request, Action <string> onSuccess) { yield return(null); yield return(null); this.Client.PostObjectAsync(request, delegate(AmazonServiceResult <PostObjectRequest, PostObjectResponse> responseObj) { if (responseObj.Exception == null) { VRC.Core.Logger.Log("object " + responseObj.Request.Key + " posted to bucket " + responseObj.Request.Bucket, DebugLevel.All); string obj = string.Format("https://s3-us-west-2.amazonaws.com/{0}/{1}", responseObj.Request.Bucket, responseObj.Request.Key); if (onSuccess != null) { onSuccess(obj); } } else { VRC.Core.Logger.Log("Exception while posting the result object", DebugLevel.Always); VRC.Core.Logger.Log("receieved error " + responseObj.Response.HttpStatusCode.ToString(), DebugLevel.Always); } }, null); yield break; }
public void PostObject() { try { PostObjectRequest request = new PostObjectRequest(bucket, commonKey, smallFileSrcPath); List <string> headers = new List <string>(); headers.Add("Host"); request.SetCosProgressCallback(delegate(long completed, long total) { Console.WriteLine(String.Format("progress = {0} / {1} : {2:##.##}%", completed, total, completed * 100.0 / total)); }); //设置policy request.SetPolicy(null); //执行请求 PostObjectResult result = cosXml.PostObject(request); Console.WriteLine(result.GetResultInfo()); } catch (COSXML.CosException.CosClientException clientEx) { Console.WriteLine("CosClientException: " + clientEx.Message); Assert.True(false); } catch (COSXML.CosException.CosServerException serverEx) { Console.WriteLine("CosServerException: " + serverEx.GetInfo()); Assert.True(false); } }
void UploadFileAsync() { Debug.Log("Retrieving file"); var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read); Debug.Log("Creating request object"); var request = new PostObjectRequest() { Bucket = bucket, Key = fileName, InputStream = stream, CannedACL = S3CannedACL.Private, // Amazon examples don't include this line. Without it, PostObjectAsync fails silently. Region = region }; Debug.Log("Making POST call"); s3Client.PostObjectAsync(request, (responseObj) => { if (responseObj.Exception == null) { Debug.Log("success " + responseObj.Request.Key + " " + responseObj.Request.Bucket); } else { Debug.Log("error " + responseObj.Response.HttpStatusCode.ToString()); } }); }
public void UploadToS3(string path, string caseID) { Debug.Log("Retrieving the file..."); FileStream stream = new FileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite); PostObjectRequest request = new PostObjectRequest() { Bucket = "caseserviceadjustmentappfiles", Key = "case_data/case_" + caseID, InputStream = stream, CannedACL = S3CannedACL.Private, Region = _S3Region }; S3Client.PostObjectAsync(request, (responseObj) => { if (responseObj.Exception == null) { Debug.Log("Successfully posted the case to bucket."); } else { Debug.Log("Exception Occured during uploading: " + responseObj.Exception); } }); SceneManager.LoadScene(0); }
public void Post(string path, string fileName) { loadingScreen.SetActive(true); botones.SetActive(false); //path = path + Path.DirectorySeparatorChar + fileName; var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read); var request = new PostObjectRequest() { Bucket = S3BucketName, Key = fileName, InputStream = stream, CannedACL = S3CannedACL.Private, Region = _S3Region }; Client.PostObjectAsync(request, (responseObj) => { if (responseObj.Exception == null) { print(string.Format("object {0} posted to bucket {1}", responseObj.Request.Key, responseObj.Request.Bucket)); StartCoroutine(GetRequest("http://localhost:5000/" + fileName)); } else { print("Exception while posting the result object"); print(string.Format("receieved error {0}", responseObj.Response.HttpStatusCode.ToString())); } }); }
/// POST 方式上传对象 public void PostObject() { //.cssg-snippet-body-start:[post-object] try { string bucket = "examplebucket-1250000000"; //存储桶,格式:BucketName-APPID string key = "exampleobject"; //对象键 string srcPath = @"temp-source-file"; //本地文件绝对路径 PostObjectRequest request = new PostObjectRequest(bucket, key, srcPath); //设置进度回调 request.SetCosProgressCallback(delegate(long completed, long total) { Console.WriteLine(String.Format("progress = {0:##.##}%", completed * 100.0 / total)); }); //执行请求 PostObjectResult result = cosXml.PostObject(request); //请求成功 Console.WriteLine(result.GetResultInfo()); } catch (COSXML.CosException.CosClientException clientEx) { //请求失败 Console.WriteLine("CosClientException: " + clientEx); } catch (COSXML.CosException.CosServerException serverEx) { //请求失败 Console.WriteLine("CosServerException: " + serverEx.GetInfo()); } //.cssg-snippet-body-end }
protected void InvokeS3Post(PostObjectRequest publicrequest, AmazonServiceCallback callback, object state) { AsyncResult asyncResult = new AsyncResult(new DefaultRequest(publicrequest, "Amazon.S3"), publicrequest, callback, state, new S3Signer(), null); try { asyncResult.Metrics.StartEvent(Metric.ClientExecuteTime); asyncResult.Request.Endpoint = DetermineEndpoint(asyncResult.Request); if (Config.LogMetrics) { asyncResult.Metrics.IsEnabled = true; asyncResult.Metrics.AddProperty(Metric.ServiceName, asyncResult.Request.ServiceName); asyncResult.Metrics.AddProperty(Metric.ServiceEndpoint, asyncResult.Request.Endpoint); asyncResult.Metrics.AddProperty(Metric.MethodName, asyncResult.RequestName); asyncResult.Metrics.AddProperty(Metric.AsyncCall, !asyncResult.CompletedSynchronously); } //ConfigureRequest(asyncResult); InvokeHelperForS3PostObject(asyncResult, publicrequest); } catch (Exception e) { AmazonLogging.LogException(AmazonLogging.AmazonLoggingLevel.Errors, "S3", e); asyncResult.IsCompleted = true; asyncResult.HandleException(e); return; } //return asyncResult; }
public void PostAudio(string fileName) { ResultText.text = "Retrieving the file"; var stream = new FileStream(Application.dataPath + _pathToAudio + fileName, FileMode.Open, FileAccess.Read, FileShare.Read); ResultText.text += "\nCreating request object"; var request = new PostObjectRequest() { Bucket = S3_BUCKET_NAME, Key = fileName, InputStream = stream, CannedACL = S3CannedACL.PublicRead, Region = _S3Region, ContentType = "audio/wav" //ContentType = "audio/wav" }; ResultText.text += "\nMaking HTTP post call"; Client.PostObjectAsync(request, (responseObj) => { if (responseObj.Exception == null) { ResultText.text += string.Format("\nobject {0} posted to bucket {1}", responseObj.Request.Key, responseObj.Request.Bucket); Debug.Log(URL_FIRST_PARTH + fileName); } else { Debug.Log(responseObj.Exception); ResultText.text += "\nException while posting the result object"; ResultText.text += string.Format("\n receieved error {0}", responseObj.Response.HttpStatusCode.ToString()); } }); }
private void PostResponseHelper(IAsyncResult result) { IAsyncExecutionContext executionContext = result.AsyncState as IAsyncExecutionContext; IWebResponseData response = executionContext.ResponseContext.HttpResponse; RuntimeAsyncResult asyncResult = executionContext.ResponseContext.AsyncResult as RuntimeAsyncResult; if (executionContext.ResponseContext.AsyncResult.Exception == null) { PostObjectResponse postResponse = new PostObjectResponse(); postResponse.HttpStatusCode = response.StatusCode; postResponse.ContentLength = response.ContentLength; if (response.IsHeaderPresent(HeaderKeys.XAmzRequestIdHeader)) { postResponse.RequestId = response.GetHeaderValue(HeaderKeys.XAmzRequestIdHeader); } if (response.IsHeaderPresent(HeaderKeys.XAmzId2Header)) { postResponse.HostId = response.GetHeaderValue(HeaderKeys.XAmzId2Header); } if (response.IsHeaderPresent(HeaderKeys.XAmzVersionIdHeader)) { postResponse.VersionId = response.GetHeaderValue(HeaderKeys.XAmzVersionIdHeader); } PostObjectRequest request = executionContext.RequestContext.OriginalRequest as PostObjectRequest; asyncResult.Request = request; asyncResult.Response = postResponse; } asyncResult.Exception = executionContext.ResponseContext.AsyncResult.Exception; asyncResult.Action = executionContext.RequestContext.Action; asyncResult.InvokeCallback(); }
/// <summary> /// Upload data to Amazon S3 using HTTP POST. /// </summary> /// <remarks> /// For more information, <see href="http://docs.aws.amazon.com/AmazonS3/latest/dev/UsingHTTPPOST.html"/> /// </remarks> /// <param name="request">Request object which describes the data to POST</param> /// <param name="callback">An Action delegate that is invoked when the operation completes.</param> /// <param name="options">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> public void PostObjectAsync(PostObjectRequest request, AmazonServiceCallback <PostObjectRequest, PostObjectResponse> callback, AsyncOptions options = null) { options = options ?? new AsyncOptions(); Action <AmazonWebServiceRequest, AmazonWebServiceResponse, Exception, AsyncOptions> callbackHelper = (AmazonWebServiceRequest req, AmazonWebServiceResponse res, Exception ex, AsyncOptions ao) => { AmazonServiceResult <PostObjectRequest, PostObjectResponse> responseObject = new AmazonServiceResult <PostObjectRequest, PostObjectResponse>((PostObjectRequest)req, (PostObjectResponse)res, ex, ao.State); if (callback != null) { callback(responseObject); } }; ThreadPool.QueueUserWorkItem(new WaitCallback(delegate { // Provide a default policy if user doesn't set it. try { InferContentType(request); if (request.SignedPolicy == null) { CreateSignedPolicy(request); } PostObject(request, options, callbackHelper); } catch (Exception e) { callback(new AmazonServiceResult <PostObjectRequest, PostObjectResponse>(request, null, e, options.State)); } })); }
// Post object into S3 with given bucket/file name public void PostObject(string bucket, string key, string tmpFile) { FileStream stream = new FileStream(tmpFile, FileMode.Open, FileAccess.Read, FileShare.Read); PostObjectRequest req = new PostObjectRequest() { Bucket = bucket, Key = key, InputStream = stream, CannedACL = S3CannedACL.Private, Region = _region }; Client.PostObjectAsync(req, (cb) => { if (cb.Exception != null) { Debug.Log(cb.Exception); stream.Dispose(); File.Delete(tmpFile); return; } Debug.Log("Successful save: " + key); File.Delete(tmpFile); }); }
/// <summary> /// Post Object to S3 Bucket. /// </summary> public void PostObject() { ResultText.text = "Retrieving the file"; string fileName = GetFileHelper(); var stream = new FileStream(Application.persistentDataPath + Path.DirectorySeparatorChar + fileName, FileMode.Open, FileAccess.Read, FileShare.Read); ResultText.text += "\nCreating request object"; var request = new PostObjectRequest() { Bucket = S3BucketName, Key = fileName, InputStream = stream, CannedACL = S3CannedACL.Private }; ResultText.text += "\nMaking HTTP post call"; Client.PostObjectAsync(request, (responseObj) => { if (responseObj.Exception == null) { ResultText.text += string.Format("\nobject {0} posted to bucket {1}", responseObj.Request.Key, responseObj.Request.Bucket); } else { ResultText.text += "\nException while posting the result object"; ResultText.text += string.Format("\n receieved error {0}", responseObj.Response.HttpStatusCode.ToString()); } }); }
public string UploadFile(FileType type, Stream stream, string fileName) { //string urlPathToFile = EMPTY_URL; var request = new PostObjectRequest() { Bucket = S3_BUCKET_NAME, Key = fileName, InputStream = stream, CannedACL = S3CannedACL.PublicRead, Region = _S3Region, ContentType = GetContentType(type) }; Client.PostObjectAsync(request, (responseObj) => { if (responseObj.Exception == null) { //Debug.Log(URL_FIRST_PARTH + fileName); } else { //Debug.Log(responseObj.Exception); } }); return(URL_FIRST_PARTH + fileName); }
void PostObjectToAWS(string path) { //FileStream stream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite); FileStream stream = File.OpenRead(path); string keyValue = "case" + UIManager.Instance.activeCase.caseID + ".dat"; PostObjectRequest request = new PostObjectRequest() { Bucket = bucketValue, Key = keyValue, InputStream = stream, CannedACL = S3CannedACL.Private, Region = RegionEndpoint.USEast2 }; S3Client.PostObjectAsync(request, (responseObj) => { if (responseObj.Exception == null) { Debug.Log("\nAWS object " + responseObj.Request.Key + " posted to bucket " + responseObj.Request.Bucket); stream.Close(); File.Delete(path); stream.Dispose(); } else { Debug.Log("****** AWS post exception!::\n"); Debug.Log(responseObj.Exception.ToString()); stream.Close(); File.Delete(path); stream.Dispose(); } }); }
public string UploadFile(FileType type, string pathToFile, string fileName) { //string urlPathToFile = EMPTY_URL; var stream = new FileStream(/*Application.dataPath + */ pathToFile + fileName, FileMode.Open, FileAccess.Read, FileShare.Read); var request = new PostObjectRequest() { Bucket = S3_BUCKET_NAME, Key = fileName, InputStream = stream, CannedACL = S3CannedACL.PublicRead, Region = _S3Region, ContentType = GetContentType(type) }; Client.PostObjectAsync(request, (responseObj) => { if (responseObj.Exception == null) { //urlPathToFile = URL_FIRST_PARTH + fileName; } else { //Debug.Log(responseObj.Exception); } }); print(URL_FIRST_PARTH + fileName); return(URL_FIRST_PARTH + fileName); }
public void PostObject(string path, string caseID) { var stream = new FileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite); PostObjectRequest request = new PostObjectRequest() { Bucket = bucketName, Key = "case#" + caseID, InputStream = stream, CannedACL = S3CannedACL.Private, Region = _S3Region }; S3Client.PostObjectAsync(request, (responseObj) => { if (responseObj.Exception == null) { Debug.Log("Successfuly posted to Bucket"); SceneManager.LoadScene(SceneManager.GetActiveScene().name); } else { Debug.LogError("Exception occured during uploading: " + responseObj.Exception); } } ); }
public IEnumerator SaveThumbnailToS3() { yield return(new WaitForSeconds(1)); VideoPlayer player = ImageTarget.GetComponent <VideoPlayer> (); player.Play(); yield return(new WaitForSeconds(1)); while (player.texture == null) { yield return(null); } Texture texture = player.texture; RenderTexture Rtexture = texture as RenderTexture; RenderTexture.active = Rtexture; Texture2D myTexture2d = new Texture2D(texture.width, texture.height); myTexture2d.ReadPixels(new Rect(0, 0, Rtexture.width, Rtexture.height), 0, 0); myTexture2d.Apply(); RenderTexture.active = null; byte[] thumbnail = myTexture2d.EncodeToPNG(); player.Stop(); MemoryStream stream = new MemoryStream(thumbnail); string videoName2 = videoName.Replace("\"", ""); string videoName3 = videoName2.Replace(".mov", ".png"); //prepares request to amazon var request = new PostObjectRequest() { Bucket = S3BucketName, Key = videoName3, InputStream = stream, CannedACL = S3CannedACL.Private, Region = _S3Region }; Debug.Log(Client); Client.PostObjectAsync(request, (responseObj) => { if (responseObj.Exception == null) { //successfully posted Debug.Log(string.Format("\nobject {0} posted to bucket {1}", responseObj.Request.Key, responseObj.Request.Bucket)); } else { //did not post Debug.Log("\nException while posting the result object"); Debug.Log(responseObj.Exception.Message); } }); }
private void GzipPostTestInner() { var contentType = "application/x-gzip"; var contentEncoding = "gzip"; var key = string.Format(GzipFileNameFormat, DateTime.Now.Ticks); AutoResetEvent ars = new AutoResetEvent(false); Exception responseException = new Exception(); string fileName = string.Format(GzipFileNameFormat, DateTime.Now.Ticks); TextAsset gzippedFile = null; byte[] buffer = null; UnityRequestQueue.Instance.ExecuteOnMainThread(() => { gzippedFile = Resources.Load("gzipFile") as TextAsset; buffer = gzippedFile.bytes; ars.Set(); }); ars.WaitOne(); var memoryStream = new MemoryStream(buffer); var request = new PostObjectRequest() { Key = fileName, Bucket = BucketName, InputStream = memoryStream, CannedACL = S3CannedACL.Private }; request.Headers.ContentEncoding = contentEncoding; request.Headers.ContentType = contentType; Client.PostObjectAsync(request, (response) => { responseException = response.Exception; ars.Set(); }, new AsyncOptions { ExecuteCallbackOnMainThread = true }); ars.WaitOne(); Assert.IsNull(responseException); var gotten = S3TestUtils.GetObjectHelper(Client, BucketName, fileName); Utils.AssertTrue(string.Compare(gotten.Headers.ContentType, contentType, true) == 0, string.Format("content types: {0} != {1}", gotten.Headers.ContentType, contentType)); // Unity removes the Content-Encoding header after unzipping :(. //Utils.AssertTrue(string.Compare(gotten.Headers.ContentEncoding, contentEncoding, true) == 0); }
/// <summary> /// Post S3 Object /// This fucntion can only be called in main thread /// </summary> /// <param name="S3PostUploadRequest"> Post Object request </param> /// <param name="callback"> Call back function is fired after async operation is completed </param> public void PostObjectAsync(PostObjectRequest request, AmazonServiceCallback callback, object state) { if (!AmazonInitializer.IsInitialized) { throw new Exception("AWSPrefab is not added to the scene"); } ThreadPool.QueueUserWorkItem(new WaitCallback(delegate { InvokeS3Post(request, callback, state); })); return; }
public void PostObject(string S3logtFileName, string localLogFileName, string logData) { /// /// Sachin... let's discuss what to use here for the userID and the 'logFileText' argument when in WebGL - i.e. the same 'stream' when in PC /// string userID = LogDB.instance.PlayerID; // SystemManager.userID.ToString(); #if UNITY_WEBGL && !UNITY_EDITOR AWSUploadToS3(S3logtFileName, logData); #else //ResultText.text = "Retrieving the file"; string fileName = ""; if (localLogFileName != "") { fileName = localLogFileName; } else { fileName = Application.dataPath + "/playerLog_/playerLog_" + userID + ".json"; //objectFileName; } var stream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read); //ResultText.text += "\nCreating request object"; var request = new PostObjectRequest() { Region = _S3Region, Bucket = S3BucketName, Key = S3logtFileName, InputStream = stream, CannedACL = S3CannedACL.Private }; //ResultText.text += "\nMaking HTTP post call"; Client.PostObjectAsync(request, (responseObj) => { if (responseObj.Exception == null) { //ResultText.text += string.Format("\nobject {0} posted to bucket {1}", responseObj.Request.Key, responseObj.Request.Bucket); Debug.Log(string.Format("Object {0} posted to Bucket {1}", responseObj.Request.Key, responseObj.Request.Bucket)); } else { //ResultText.text += "\nException while posting the result object"; //ResultText.text += string.Format("\n receieved error {0}", responseObj.Response.HttpStatusCode.ToString()); Debug.Log(string.Format("Receieved Error {0}", responseObj.Response.HttpStatusCode.ToString())); } }); #endif }
public void AddTencentCos(string path, OnProgressCallback postpath, string name) { CosXmlConfig config = new CosXmlConfig.Builder() .SetConnectionTimeoutMs(SetConnectionTimeoutMs) //设置连接超时时间,单位毫秒,默认45000ms .SetReadWriteTimeoutMs(SetReadWriteTimeoutMs) //设置读写超时时间,单位毫秒,默认45000ms .IsHttps(IsHttps) //设置默认 HTTPS 请求 .SetAppid(SetAppid) //设置腾讯云账户的账户标识 APPID .SetRegion(SetRegion) //设置一个默认的存储桶地域 .Build(); string secretId = SecretId; //云 API 密钥 SecretId string secretKey = SecretKey; //云 API 密钥 SecretKey long durationSecond = 60000; //每次请求签名有效时长,单位为秒 QCloudCredentialProvider qCloudCredentialProvider = new DefaultQCloudCredentialProvider(secretId, secretKey, durationSecond); CosXml cosXml = new CosXmlServer(config, qCloudCredentialProvider); try { string bucket = "yuanguhl"; //存储桶,格式:BucketName-APPID string key = $"{DateTime.Now.ToString("yy")}/Add/" + name; //对象在存储桶中的位置,即称对象键 string srcPath = path; //本地文件绝对路径 if (!File.Exists(srcPath)) { // 如果不存在目标文件,创建一个临时的测试文件 File.WriteAllBytes(srcPath, new byte[1024]); } PostObjectRequest request = new PostObjectRequest(bucket, key, srcPath); request.Region = "ap-beijing"; //设置签名有效时长 request.SetSign(TimeUtils.GetCurrentTime(TimeUnit.SECONDS), 600); //设置进度回调 request.SetCosProgressCallback(postpath); //执行请求 PostObjectResult result = cosXml.PostObject(request); //请求成功 } catch (COSXML.CosException.CosClientException clientEx) { //请求失败 throw clientEx; } catch (COSXML.CosException.CosServerException serverEx) { //请求失败 throw serverEx; } }
/// <summary> /// Post Object to S3 Bucket. /// </summary> public void PostObject() { print("Retrieving the file"); string fileName = GetFileHelper(); // print ("!!! FILE PATH: " + Application.persistentDataPath + Path.DirectorySeparatorChar + fileName); // var stream = new FileStream(Application.persistentDataPath + Path.DirectorySeparatorChar + fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite); var stream = new FileStream(Application.persistentDataPath + Path.DirectorySeparatorChar + fileName, FileMode.Open, FileAccess.Read, FileShare.Read); print("\nCreating request object"); // print("+= string.Format("\n TEST FORMATTING: {0}", "butt"); var request = new PostObjectRequest() { Bucket = S3BucketName, Key = fileName, InputStream = stream, CannedACL = S3CannedACL.Private, // CannedACL = S3CannedACL.PublicReadWrite,// Private Region = _S3Region }; print("\nMaking HTTP post call"); Client.PostObjectAsync(request, (responseObj) => { if (responseObj.Exception == null) { print("\nPosted Object Success"); print("\nobject " + responseObj.Request.Key + " posted to bucket " + responseObj.Request.Bucket); } else { print("!!! POST EXCEPTION: " + responseObj.Exception.Message); print("\nException while posting the result object"); print("\nException: " + responseObj.Exception.Message); // print("+= "\nException while posting the result object"; // print("+= "\nH: " + responseObj.Response. .Response.HttpStatusCode.ToString(); print("\n receieved error " + responseObj.Response.HttpStatusCode.ToString()); } }); }