Download Zip file with Webclient c# with POST method - c#

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

Related

Video Upload API only works with 1 file type?

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");
}

How to Export an Excel File using C#

Helo, i already search on Google and here (StackOverflow) but no any solution i complete.
I Have a Excel file in my folder and i need to create a method on my controller to download this file.
And in my React Web Site i need to get this file to user computer.
I try to use ActionResult, FileStreamResult, HttpResponseMessage and other, read file from folder with File.ReadAllbytes, put the Header on response.
On the final i get this.
{ FileContents: "allcontentoffilehere....", Contenttype: "application/octet-stream", FileDownloadName: "filename.xls"}
And using this JavaScript do download:
var bytes = new Uint8Array(responseDownloadFile.data.FileContents);
var blob = new Blob([bytes], {
type: responseDownloadFile.data.ContentType
});
const link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = responseDownloadFile.data.FileDownloadName;
document.body.appendChild(link);
link.click();
But the file when download is corrupted.
Any on can help me?
Try to return HttpResponseMessage type on your API
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
result.Content = new ByteArrayContent([file bytes]);
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/file type");
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = "filename.xlsx"
};
return result;
And on your Front end execute code:
window.location.href = "link to your api endpoint to download excel";

AWS C# lambda File upload to S3

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.

Edit file on server with PHP and C#

Here is my C# code:
WebClient myClient = new WebClient();
NameValueCollection inputs = new NameValueCollection();
inputs.Add("decrement", "true");
System.Uri uri = new System.Uri ("http://myserver/myPHP.php");
myClient.UploadValuesAsync (uri, "POST", inputs);
Here is my myPHP.php file on the server:
if($_POST['decrement'] == "true") {
$file = './myTextFile.txt';
// Open the file to get existing content
$current = file_get_contents($file);
// Append a new person to the file
$current .= "John Smith\n";
// Write the contents back to the file
file_put_contents($file, $current);
}
The txt file is not being written to, why not?
NOTE: myPHP.php and myTextFile.txt are in the same directory on the server
If your file is directly under htdocs:
$file = $_SERVER['DOCUMENT_ROOT'] . '/myTextFile.txt';

Howto: download a file keeping the original name in C#?

I have files on a server that can be accessed from a URL formatted like this:
http:// address/Attachments.aspx?id=GUID
I have access to the GUID and need to be able to download multiple files to the same folder.
if you take that URL and throw it in a browser, you will download the file and it will have the original file name.
I want to replicate that behavior in C#. I have tried using the WebClient class's DownloadFile method, but with that you have to specify a new file name. And even worse, DownloadFile will overwrite an existing file. I know I could generate a unique name for every file, but i'd really like the original.
Is it possible to download a file preserving the original file name?
Update:
Using the fantastic answer below to use the WebReqest class I came up with the following which works perfectly:
public override void OnAttachmentSaved(string filePath)
{
var webClient = new WebClient();
//get file name
var request = WebRequest.Create(filePath);
var response = request.GetResponse();
var contentDisposition = response.Headers["Content-Disposition"];
const string contentFileNamePortion = "filename=";
var fileNameStartIndex = contentDisposition.IndexOf(contentFileNamePortion, StringComparison.InvariantCulture) + contentFileNamePortion.Length;
var originalFileNameLength = contentDisposition.Length - fileNameStartIndex;
var originalFileName = contentDisposition.Substring(fileNameStartIndex, originalFileNameLength);
//download file
webClient.UseDefaultCredentials = true;
webClient.DownloadFile(filePath, String.Format(#"C:\inetpub\Attachments Test\{0}", originalFileName));
}
Just had to do a little string manipulation to get the actual filename. I'm so excited. Thanks everyone!
As hinted in comments, the filename will be available in Content-Disposition header. Not sure about how to get its value when using WebClient, but it's fairly simple with WebRequest:
WebRequest request = WebRequest.Create("http://address/Attachments.aspx?id=GUID");
WebResponse response = request.GetResponse();
string originalFileName = response.Headers["Content-Disposition"];
Stream streamWithFileBody = response.GetResponseStream();

Categories

Resources