I have created a Serverless for AWS using visual studio empty template. I am trying to send a file to it which internally gets uploaded to S3 using C#. I am able to upload the file through a console application. I need help on:
a. how to send file to API through Insomnia or Postman -- able to do it now
b. How the receive the file so that when I upload it S3 I am able to download it directly the way I sent in the API.-- able to do it now
[EDIT]
c. When trying to save the file to bucket the file size is less than the uploaded and is corrupted.
Code Snippet:
public APIGatewayProxyResponse Get(APIGatewayProxyRequest request, ILambdaContext context)
{
context.Logger.LogLine(Encoding.ASCII.GetByteCount(request.Body).ToString());
MemoryStream ms = new MemoryStream();
TransferUtility utility = new TransferUtility(new AmazonS3Client("<AccessKey>", "<SecretKey>", Amazon.RegionEndpoint.USEast1));
var checker = new TransferUtilityUploadRequest()
{
InputStream = new MemoryStream(Encoding.ASCII.GetBytes(request.Body)),
BucketName = "<BucketName>",
Key = "<FileName>.pdf"
};
utility.Upload(checker);
var response = new APIGatewayProxyResponse
{
StatusCode = (int)HttpStatusCode.OK,
Body = JsonConvert.SerializeObject(checker),
Headers = new Dictionary<string, string> { { "Content-Type", "application/json" }, { "Access-Control-Allow-Origin", "*" } }
};
return response;
}
Note: The file could be docx or pdf. Also I have the code to upload file stream to S3 Just need info on receiving the file through APIGatewayProxyRequest type and converting to stream.
Thanks in advance.
Related
I have a script that uploads a video to an API I built, and after it processes on the API side, a text file is returned to the client. The strange thing is, this only works with one type of file, a .QT file extension. Any other video type I try to send sends and empty video. I have tried .mov, .mp4, and .qt and only the .qt uploads properly. I'll post my code below. Would anyone know what cause only the one file type to work? Nothing on the API side singles out the qt file. I believe this is an issue with this script.
public async void Function() {
Debug.Log("works1");
string filePath = "IMG_0491.mov";
//string filePath = ProcessMode.theFilePath;
var client = new HttpClient();
using (var multipartFormContent = new MultipartFormDataContent()) {
//Add the file
Debug.Log("works2");
var fileStreamContent = new StreamContent(File.OpenRead(filePath));
Debug.Log("works3");
fileStreamContent.Headers.ContentType = new MediaTypeHeaderValue("video/mov");
multipartFormContent.Add(fileStreamContent, name: "file", fileName: filePath); //Originally Actual "Name`
//Send it
var response = await client.PostAsync("http://127.0.0.1:5000/", multipartFormContent); //Enter IP and Port of API when set up
Debug.Log("works4");
//Ensure it was successful.
response.EnsureSuccessStatusCode();
//Grab the animation data from the content.
var animation_data = await response.Content.ReadAsStringAsync();
Debug.Log(animation_data);
//Save to file.
//File.WriteAllTextAsync("AnimationFile.txt", animation_data);
await File.WriteAllTextAsync("AnimationFile.txt", animation_data);
Debug.Log("works5");
}
I have build an API which gives output in zip file when more than one file is requested
Now I have to download this zip file in C# WPF app.
To access API, we have to use POST ( instead of GET ) and JSON parameters.
I am able to download one file as string with help of below code
WebClient client = new WebClient();
var vm = new { from = "A", to = "S", files= "all", type = "csv", file = "Single" };
client.Headers[HttpRequestHeader.ContentType] = "application/json";
var dataString = JsonConvert.SerializeObject(vm);
var response = client.UploadData("https://myurl.com/data", "POST", System.Text.Encoding.ASCII.GetBytes(dataString));
But not able to figure out how to download zip file and save it to disk
I am trying to download a simple xlsx file using web api but the file is always corrupt and I am yet to figure out why.I am using C# ClosedXML.Excel and following a basic example which can be found here:
ClosedXml examples
[HttpGet]
[Route("campaigns/{id}/contact-points/excel")]
[SwaggerResponse(491, "TokenInvalid")]
[SwaggerResponse(HttpStatusCode.NotFound)]
[SwaggerResponse(HttpStatusCode.Forbidden)]
[ResponseType(typeof(HttpResponseMessage))]
public async Task<IHttpActionResult> GetCampaignContactPointsExcel(int id, int frequency, string txtFrequency)
{
var wb = new XLWorkbook();
var ws1 = wb.Worksheets.Add("Sheet1");
ws1.Cell("A1").SetValue(1).AddToNamed("value1");
var ws2 = wb.Worksheets.Add("Sheet2");
ws2.Cell("A1").SetFormulaA1("=value1").AddToNamed("value2");
var responseMessage = new HttpResponseMessage(HttpStatusCode.OK);
using (var memoryStream = new MemoryStream())
{
wb.SaveAs(memoryStream);
responseMessage.Content = new ByteArrayContent(memoryStream.ToArray());
responseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
responseMessage.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = "ContactPoints.xlsx"
};
memoryStream.Close();
}
return ResponseMessage(responseMessage);
}
I am also using swagger and when I click on the link it downloads the file and opens it as a xlsx file but it always says it's corrupt.
There is nothing wrong in the backend code. On the frontend side you need to set responseType='blob'
Seems like this is an issue related to swagger ui 2. Please refer to [https://github.com/swagger-api/swagger-ui/issues/1605][1].
You can try curl or Postman to see if it downloads the file correctly.
While calling the service set Response type as 'blob'
return this.http.get(this.url +'PA/Downloadexcel/'+revisionId,{ responseType :'blob'});
I'm trying to download a blob from private Azure Blob storage container and display it in an image tag.
On the question below you can see how I'm returning the blob from the Web API in Stream format.
Getting 403 error when trying to retrieve an Azure blob on Web API request
From the HTTP response, I am able to retrieve the content type of the blob by including it on the headers section of the request. To use it to generate the data URI to be used on the image tag. I understand I need to convert the Stream into a base64 string to be able to include it on the src attribute of an image tag. I'm currently struggling to convert the result from the HTTP request into a base64 string.
I have created this js fiddle which contains the data (image) received from the HTTP request along with my attempt to convert the data into a base64 string:
'http://jsfiddle.net/chesco9/6a7ohgho/'
EDIT
Thank you Tom for your help. I was able to implement your solution and it worked out. I had been stuck on this problem for a few days now.
public async Task<AzureBlobModel> DownloadBlob(Guid blobId)
{
try
{
//get picture record
Picture file = await _media.GetPictureAsync(blobId);
// get string format blob name
var blobName = file.PictureId.ToString() + file.Extension;
if (!String.IsNullOrEmpty(blobName))
{
var blob = _container.GetBlockBlobReference(blobName);
// Strip off any folder structure so the file name is just the file name
var lastPos = blob.Name.LastIndexOf('/');
var fileName = blob.Name.Substring(lastPos + 1, blob.Name.Length - lastPos - 1);
var fileLength = blob.Properties.Length;
var stream = await blob.OpenReadAsync();
MemoryStream ms = new MemoryStream();
stream.CopyTo(ms);
var result = new AzureBlobModel()
{
FileName = fileName,
FileSize = blob.Properties.Length,
Stream = stream,
ContentType = blob.Properties.ContentType,
StreamBase64 = Convert.ToBase64String(ms.ToArray())
};
return result;
}
}
catch(Exception ex)
{
await _log.CreateLogEntryAsync("exception thrown: " + ex.ToString());
}
await _log.CreateLogEntryAsync("returning null");
// Otherwise
return null;
}
I'm currently struggling to convert the result from the HTTP request into a base64 string.
Base on my understanding, now you can download the blob from the Azure storage.
According to your mentioned link, the WebApi return the AzureBlobModel.
We can convert the stream to base64 string easily with C# code backend.You can add following code in your code. If it is prossible, return this value in the AzureBlobModel.
MemoryStream ms = new MemoryStream();
stream.CopyTo(ms);
string strBase64 = Convert.ToBase64String(ms.ToArray());
I am using .NET SDK for Amazon S3 in my Windows Phone 8 project. I am using the following code,
public async void UploadFile(string bucketName, string filepath)
{
string awsID = "myID";
string secretKey = "mysecretkey";
AmazonS3Client s3Client = new AmazonS3Client(awsID, secretKey);
var request = new PutObjectRequest()
{
BucketName = "bucketname",
InputStream = App.GetResourceStream(new Uri("projectname;component/Assets/call.png", UriKind.Relative)).Stream
};
await s3Client.PutObjectAsync(request);
Console.WriteLine("File Uploaded");
}
I have set the content type of image as "Resource"
I am getting this error
XML is malformed from amazon s3.
On googling i found a links3-put fails to send file asking me to append filename with name of the bucket.On doing so,I know get a folder created inside my bucket int he name of file and my contents are not uploaded.
For WinRT and Windows Phone FilePath property must be in the form of "ms-appdata:///local/file.txt" as mentioned here.
To upload from isolated storage you can use InputStream property.
var request = new PutObjectRequest()
{
BucketName = "bucketname",
InputStream = IsolatedStorageFile.GetUserStoreForApplication().OpenFile("YOUR_FILE_PATH", FileMode.Open);
};