I am trying to access the file that has been uploaded to Amazon S3 by using the method GetPreSignedUrlRequest. The code I am using is as below:-
string bucketName = string.Empty;
if (ConfigurationManager.AppSettings["S3BucketName"] != null)
{
bucketName = ConfigurationManager.AppSettings["S3BucketName"].ToString();
}
AmazonS3Client s3Client = new AmazonS3Client(Amazon.RegionEndpoint.USEast1);
GetPreSignedUrlRequest request = new GetPreSignedUrlRequest
{
BucketName = bucketName,
Key = file.FileName,
Expires = DateTime.Now.AddMinutes(5),
Protocol = Protocol.HTTP
};
string url = s3Client.GetPreSignedURL(request);
The url generated by this is then used to point to the file.
It looks like
http://s3.amazonaws.com/mybucketname/VZcbKsZgR2qyOMkLU1XT_jquery_ui_touch-punch_min_js.txt?X-Amz-Expires=300&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAIMGQJ6D5L5SNBGHA/20140114/us-east-1/s3/aws4_request&X-Amz-Date=20140114T194159Z&X-Amz-SignedHeaders=host&X-Amz-Signature=922719dd2286600aebaca5701a8e142d327342b541569c9a4d7d8afc822d9a76/VZcbKsZgR2qyOMkLU1XT_jquery_ui_touch-punch_min_js.txt
But that gives me signature doesnot match error as shown in the image below:-
Update - version 2.0.6 of the SDK, released Jan 16th, contains a fix for this issue.
Your code is fine, unfortunately a bug in the SDK is causing the presigned url to be malformed. I've just tested it with our latest codebase and we've fixed the issue; this new version should be released soon.
I'll ping this issue once we release the patch. Sorry for the inconvenience.
Regards,
This can also occur if some of the details about the request are not set up properly:
e.g. For me the following lines fixed the problem
request1.ContentType = "image/jpeg";
request1.Verb = HttpVerb.PUT;
Related
In my DownloadFile page's Page_Load method, the filename a user wishes to download is retrieved from the query string. The file is hosted in an Azure Blob Storage account. I am attempting to download the file using shared access signatures (SAS) via this approach:
var containerName = "containerName";
var con = "connectionString";
CloudStorageAccount account = CloudStorageAccount.Parse(con);
var blobClient = account.CreateCloudBlobClient();
var container = blobClient.GetContainerReference(containerName);
var blob = container.GetBlockBlobReference("file.pdf");
var sasToken = blob.GetSharedAccessSignature(new SharedAccessBlobPolicy()
{
Permissions = SharedAccessBlobPermissions.Read,
SharedAccessExpiryTime = DateTime.UtcNow.AddMinutes(10),
}, new SharedAccessBlobHeaders()
{
ContentDisposition = "attachment; filename=file.pdf"
});
var blobUrl = string.Format("{0}{1}", blob.Uri.AbsoluteUri, sasToken);
Response.Redirect(blobUrl);
However, this does not download the file. Instead, the browser just shows a garbled character stream of the file:
The blobUrl appears to be valid. But the Response.Redirect isn't working as expected. Am I doing something wrong?
Note: I am using WebForms (unfortunately), not MVC
I was able to figure out a workaround by using an iframe. If I add an iframe to the page:
<iframe id="iframeFile" runat="server" style="display:none;"></iframe>
Then set the source in the codefile:
iframeFile.Src = blobUrl;
It downloads the file.
This may not be ideal, and I'm still not sure why Response.Redirect isn't working as expected. So I'm certainly open to other suggestions as well. But this workaround does resolve the issue of not being able to download the file.
I'm trying to upload an image file to aws s3 storage and get back that image URL. I'm using secret key and access key to create credentials. But when the program runs it it says
"Unable to find credentials" .
Here is my code which i used.
public string sendMyFileToS3(string from,string to, string bucketName, string fileName)
{
BasicAWSCredentials awsCreds = new BasicAWSCredentials(bucketName, fileName);
AmazonS3Client client = new AmazonS3Client(awsCreds);
TransferUtility utility = new TransferUtility(client);
TransferUtilityUploadRequest request = new TransferUtilityUploadRequest();
request.BucketName = bucketName;
request.Key = fileName;
request.FilePath = from;
utility.Upload(request);
string urlString = "";
GetPreSignedUrlRequest request1 = new GetPreSignedUrlRequest
{
BucketName = bucketName,
Key = fileName,
Expires = DateTime.Now.AddYears(2)
};
urlString = client.GetPreSignedURL(request1);
Console.WriteLine(urlString);
File.Move(from, to);
return urlString ;
}
In order to create an S3 Client you need to provide your credentials, the region and endpoint:
AWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey);
AmazonS3Config config = new AmazonS3Config();
config.ServiceURL = "s3.amazonaws.com";
config.RegionEndpoint = Amazon.RegionEndpoint.GetBySystemName("us-east-1");
client = new AmazonS3Client(credentials, config);
The possible regions are listed here, and depend on where you created your bucket being us-east-1 the default value.
While the possible endpoints are this three:
s3.amazonaws.com
s3-accelerate.amazonaws.com
s3-accelerate.dualstack.amazonaws.com
The first one being the standard one since the others need you to configure your bucket like it's explained here.
I am going to take a guess and say you have a conflict between the credentials your app is using and other credentials you may have installed onto your dev or test machine, i.e. in the credentials file or your app.config.
I would check and make sure you are only using a single method to provide those credentials to the program.
THis link shows the priority the SDK will look for the credentials:
http://docs.aws.amazon.com/sdk-for-java/v1/developer-guide/credentials.html
How can I add a new document to Content Server 10.5 using the REST api?
I am following the Swagger docs for creating a node, but it is not clear how I attach the file to the request. Here is (roughly) the code I am using:
var folderId = 2000;
var docName = "test";
var uri = $"http://[serverName]/otcs/llisapi.dll/api/v1/nodes?type=144&parent_id={folderId}&name={docName}";
var request = new HttpRequestMessage();
request.Headers.Add("Connection", new[] { "Keep-Alive" });
request.Headers.Add("Cache-Control", "no-cache, no-store, must-revalidate");
request.Headers.Add("Pragma", "no-cache");
request.Headers.Add("OTCSTicket", /* ticket here */);
request.RequestUri = new Uri(uri);
request.Method = HttpMethod.Post;
request.Content = new ByteArrayContent(data);
request.Content.Headers.ContentType = new MediaTypeHeaderValue(MimeMapping.GetMimeMapping(filePath));
request.Headers.ExpectContinue = false;
var httpClientHandler = new HttpClientHandler
{
Proxy = WebRequest.GetSystemWebProxy(),
UseProxy = true,
AllowAutoRedirect = true
};
using (var client = new HttpClient(httpClientHandler))
{
var response = client.SendAsync(request).Result;
IEnumerable<string> temp;
var vals = response.Headers.TryGetValues("OTCSTicket", out temp) ? temp : new List<string>();
if (vals.Any())
{
this.ticket = vals.First();
}
return response.Content.ReadAsStringAsync().Result;
}
I've been searching through the developer.opentext.com forums, but finding a complete example in c# is proving tough - there are a few examples in javascript, but attempting to replicate these in c# or via chrome or firefox extensions just give the same results. Calling other CS REST methods has not been an issue so far, this is the first one that's giving me problems.
Edit: I pasted the wrong url into my question, which I've now fixed. It was var uri = $"http://[serverName]/otcs/llisapi.dll/api/v1/forms/nodes/create?type=0&parent_id={folderId}&name={docName}";.
Your URL doesn't look like the REST API, it's rather the traditional URL used for the UI.
This article should describe how to do what you want to do:
https://developer.opentext.com/webaccess/#url=%2Fawd%2Fresources%2Farticles%2F6102%2Fcontent%2Bserver%2Brest%2Bapi%2B%2Bquick%2Bstart%2Bguide&tab=501
EDITED:
Ok, so that's how it should work:
send a POST to http://www.your_content_server.com/cs[.exe]/api/v1/nodes
send this in your payload to create a document in your enterprise workspace
type=144
parent_id=2000
name=document_name.txt
<file>
A incomplete demo in Python would look like this. Make sure you get a valid ticket first.
files = {'file': (open("file.txt", 'rb')}
data = { 'type': 144, 'parent_id': 2000, 'name': 'document_name.txt' }
cs = requests.post(url, headers={'otcsticket':'xxxxxxx'}, data=data, files=files)
if cs.status_code == 200:
print "ok"
else:
print cs.text
You will need a form input to get the file onto the page then you can use filestreams to redirect it, there is great guide for that here.
Reading files in JavaScript using the File APIs
Here is a Jquery/ Ajax example.
I find the best way to go about this is to use Postman (Chrome Plugin) to experiment until you get comfortable.
var form = new FormData();
form.append("file", "*filestream*");
form.append("parent_id", "100000");
form.append("name", "NameYourCreatedFile");
form.append("type", "144");
var settings = {
"async": true,
"url": "/cs.exe/api/v1/nodes", // You will need to amend this to match your environment
"method": "POST",
"headers": {
"authorization": "Basic **use Postman to generate this**",
"cache-control": "no-cache",
},
"processData": false,
"contentType": false,
"mimeType": "multipart/form-data",
"data": form
}
$.ajax(settings).done(function (response) {
console.log(response);
});
It appears that the OpenText API only supports file uploads through asynchronous JavaScript uploads - not through traditional file uploads by using typical posted form requests that contain the files contents (which is pretty crappy to be honest - as this would be the easiest to handle on server side).
I've contacted their support and they were absolutely no help - they said since it's working with JavaScript, then they can't help me. Anyone else utilizing any language besides JavaScript is SOL. I submitted my entire API package, but they didn't bother investigating and wanted to close my ticket ASAP.
The only way I've found to do this, is to upload / send the file into your 'Upload' directory on your Content Servers web server (on ours it was set to D:\Upload).This directory location is configurable in the admin section.
Once you've sent the file to your web server, send a create node request with the file param set to the full file path of the file residing on your server, as the OpenText API will attempt to retrieve the file from this directory.
I've created a PHP API for this, and you can browse its usage here:
https://github.com/FBCLIT/OpenTextApi
<?php
use Fbcl\OpenTextApi\Client;
$client = new Client('http://server.com/otcs/cs.exe', 'v1');
$api = $client->connect('username', 'secret');
try {
// The folder node ID of where the file will be created under.
$parentNodeId = '12356';
// The file name to display in OpenText
$fileName = 'My Document.txt';
// The actual file path of the file on the OpenText server.
$serverFilePath = 'D:\Upload\My Document.txt';
$response = $api->createNodeDocument($parentNodeId, $fileName, $serverFilePath);
if (isset($response['id'])) {
// The ID of the newly created document will be returned.
echo $response['id'];
}
} catch (\Exception $ex) {
// File not found on server drive, or issue creating node from given parent.
}
MIME Type detection appears to happen automatically, and you do not need to send anything for it to detect the file type. You can name the file to whatever you like without an extension.
I have also discovered that you cannot use an IP address or Host name for uploading files in this manor. You must enter a path that is local to the server you are uploading to. You can however give just the file name that exists in the Upload directory, and the OpenText API seems to locate it fine.
For example, you can pass either D:\Uploads\Document.txt or Document.txt.
If you haven't done it correctly, you should get the error:
Client error: POST http://server.com/otcs/cs.exe/api/v1/nodes resulted in a 400 Bad Request response: {"error":"Error: File could not be found within the upload directory."}
In my county -Turkey- to upload and see images in Imgur is forbidden. When I tried to upload image with my client-id it throws a 403 Forbidden error. So I think the solution is upload using VPN. But I don't know how. I tried it as below
using (var w = new WebClient())
{
var values = new NameValueCollection
{
{"image", Convert.ToBase64String(File.ReadAllBytes(path))}
};
WebProxy pr = new WebProxy("euro217.vpnbook.com");
pr.Credentials = new NetworkCredential("vpnbook", "caPhahu4");
pr.UseDefaultCredentials = false;
pr.BypassProxyOnLocal = false;
w.Proxy = pr;
w.Headers.Add("Authorization", "Client-ID " + clid);
byte[] response = w.UploadValues("https://api.imgur.com/3/upload.xml", values);
Console.WriteLine(XDocument.Load(new MemoryStream(response)));
//now process response as you'd like. the link is encapsulated by <link></link> in the response.
}
I have found the VPN adress and credential infos from a public site. I think the informations is not wrong. But not sure.Please help!.
EDIT: I have solved the problem. The problem is I got the clientID from developer.google.com for OAuth API. I thought I was right,but I was wrong. The id must be taken from https://api.imgur.com/oauth2/addclient. This solved the issue. Thanks everyone tried to help.
I am using amazon .NET SDK in widows phone 8 app for uploading images, the code was working fine.Now I get an exception
The bucket you are attempting to access must be addressed using the
specified endpoint. Please send all future requests to this endpoint.
I have updated to latest version of SDK 2.0.2.2, Has anything changed with the update?
My code
string awsID = "myid";
string secretKey = "mysecretkey";
try{
AmazonS3Client s3Client = new AmazonS3Client(awsID, secretKey,RegionEndpoint.USWest1);
string s="";
if (IsolatedStorageSettings.ApplicationSettings.Contains("selectedphoto1"))
{
s = IsolatedStorageSettings.ApplicationSettings["selectedphoto1"] as string;
}
var InputStream = App.GetResourceStream(new Uri("appname;component/Assets /call.png", UriKind.Relative));
var request = new PutObjectRequest()
{
BucketName = "mybucketname",
ContentType="image/png",
Key=s+".jpg",
InputStream = myFileStream,
};
await s3Client.PutObjectAsync(request);
}
catch (Exception ex)
{
Console.Write(ex.InnerException);
}
This is happening because bucket region is incorrect.
Check your region on Amazon console at S3 bucket and configure the same in config file and code.
For example:
AmazonS3Client s3Client = new AmazonS3Client(awsID, secretKey, RegionEndpoint.APNortheast1);
<add key="AWSRegion" value="eu-west-1" />