I'm using AWSSDK.net. When I use the code below to download a JPG or PNG file, the file opens normally. When I download a JPEG file the file does not open. A message appears saying that the file is not recognized as an image file.
Does anyone know how to answer me how to write code using AWSSDK.net that downloads a JPEG file?
var request = new GetObjectRequest
{
BucketName = nameBucket,
Key = Path.GetFileName(filename),
};
using (var response = await client.GetObjectAsync(request))
{
await response.WriteResponseStreamToFileAsync($"{LocalFileName}", false, CancellationToken.None);
return (response.ResponseStream);
}
Related
I am Using MVC.Net application and I want to download multiple files as zipped. I have written code with memory stream and ZipArchive in my controller action method. With that code I am able to successfully download the files as zipped folder. But when I unzipped those and trying to open them then I am getting the error as below
opening word document with Microsoft word - Word found unreadable content error
opening image file(.png) - dont support file format error
Here is my controller method code to zip the files
if (sendApplicationFiles != null && sendApplicationFiles.Any())
{
using (var compressedFileStream = new MemoryStream())
{
// Create an archive and store the stream in memory.
using (var zipArchive = new ZipArchive(compressedFileStream, ZipArchiveMode.Create, true))
{
foreach (var file in sendApplicationFiles)
{
// Create a zip entry for each attachment
var zipEntry = zipArchive.CreateEntry(file.FileName);
// Get the stream of the attachment
using (var originalFileStream = new MemoryStream(file.FileData))
using (var zipEntryStream = zipEntry.Open())
{
// Copy the attachment stream to the zip entry stream
originalFileStream.CopyTo(zipEntryStream);
}
}
}
return new FileContentResult(compressedFileStream.ToArray(), "application/zip") { FileDownloadName = "Filename.zip" };
}
}
Expecting the document content should load without error
I did not investigate your code, but this link might help. There are few examples.
https://learn.microsoft.com/en-us/dotnet/standard/io/how-to-compress-and-extract-files
I hope anyone can help me, I'am new in C, I am working on making web APIs that sends files from server based on an input , When I enter an ID , I get all files related to that ID (Indesign files, jpegs, pngs, illustator files ...)
I use Postman to get the resulat and it looks like the attached fileenter image description here :
I have to copy each link and paste it to address bar to download the file.
What I want is to have only one file (Zip) that contains all files.
Is that even doable ? Thanks
I found solution and it's returning a zipfile with the correct files, the issue now that these files have 0Kb size , Help please ?
Here's my code
``
MemoryStream archiveStream = new MemoryStream();
using (ZipArchive archiveFile = new ZipArchive(archiveStream, ZipArchiveMode.Create, true))
{
foreach (var item in assetsNotDuplicated)
{
// create file streams
// add the stream to zip file
var entry = archiveFile.CreateEntry(item.Name);
using (StreamWriter sw = new StreamWriter(entry.Open()))
{
sw.Write(item.Url);
}
}
}
HttpResponseMessage responseMsg = new HttpResponseMessage(HttpStatusCode.OK);
responseMsg.Content = new ByteArrayContent(archiveStream.ToArray());
//archiveStream.Dispose();
responseMsg.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = "allfiles.zip" };
responseMsg.Content.Headers.ContentType = new MediaTypeHeaderValue("application/zip");
return responseMsg;
}
I want to download a .xlsx file from below address.
http://members.tsetmc.com/tsev2/excel/MarketWatchPlus.aspx?d=1396-08-08
by clicking on the link automatically a file will be downloaded by the browser. I tried to download the file from this codes:
using (var client = new WebClient())
{
client.DownloadFile("http://members.tsetmc.com/tsev2/excel/MarketWatchPlus.aspx?d=1396-08-08", #"D:\Archive\1396-08-08.xlsx");
}
But it will download a weird file different from the file downloaded by the browser at first step.
Also I tried :
System.Diagnostics.Process.Start(
"http://members.tsetmc.com/tsev2/excel/MarketWatchPlus.aspx?d=0");
But this code has two disadvantages:
1- It opens a browser which is not required.
2- I can't determine any path or file name for the downloaded file.
I want to gain exactly the same file that will be downloaded by clicking on the above link address.
How can I download my required file?
Lasse Vågsæther Karlsen is correct. Your browser is smart enough to decompress the file because the response contains the header:
content-encoding:"gzip"
You can download and decompress the file with this code (adjust accordingly for your file name, path, etc.)
void Main()
{
using (var client = new WebClient())
{
client.Headers.Add("accept", "*/*");
byte[] filedata = client.DownloadData("http://members.tsetmc.com/tsev2/excel/MarketWatchPlus.aspx?d=1396-08-08");
using (MemoryStream ms = new MemoryStream(filedata))
{
using (FileStream decompressedFileStream = File.Create("c:\\deleteme\\test.xlsx"))
{
using (GZipStream decompressionStream = new GZipStream(ms, CompressionMode.Decompress))
{
decompressionStream.CopyTo(decompressedFileStream);
}
}
}
}
}
I am using DotNetZip.
What I need to do is to open up a zip files with files from the server.
The user can then grab the files and store it locally on their machine.
What I did before was the following:
string path = "Q:\\ZipFiles\\zip" + npnum + ".zip";
zip.Save(path);
Process.Start(path);
Note that Q: is a drive on the server. With Process.Start, it simply open up the zip file so that the user can access all the files. I like to do the same but not store the file on disk but show it from memory.
Now, instead of storing the zip file on the server, I like to open it up with MemoryStream
I have the following but does not seem to work
var ms = new MemoryStream();
zip.Save(ms);
but not sure how to proceed further in terms of opening up the zip file from a memory stream so that the user can access all the files
Here is a live piece of code (copied verbatim) which I wrote to download a series of blog posts as a zipped csv file. It's live and it works.
public ActionResult L2CSV()
{
var posts = _dataItemService.SelectStuff();
string csv = CSV.IEnumerableToCSV(posts);
// These first two lines simply get our required data as a long csv string
var fileData = Zip.CreateZip("LogPosts.csv", System.Text.Encoding.UTF8.GetBytes(csv));
var cd = new System.Net.Mime.ContentDisposition
{
FileName = "LogPosts.zip",
// always prompt the user for downloading, set to true if you want
// the browser to try to show the file inline
Inline = false,
};
Response.AppendHeader("Content-Disposition", cd.ToString());
return File(fileData, "application/octet-stream");
}
You can use:
zip.Save(ms);
// Set read point to beginning of stream
ms.Position = 0;
ZipFile newZip = ZipFile.Read(ms);
See the documentation for Create a zip using content obtained from a stream.
using (ZipFile zip = new ZipFile())
{
ZipEntry e= zip.AddEntry("Content-From-Stream.bin", "basedirectory", StreamToRead);
e.Comment = "The content for entry in the zip file was obtained from a stream";
zip.AddFile("Readme.txt");
zip.Save(zipFileToCreate);
}
After saving it, you can then open it up as normal.
Basically, the app displays images, and I want the user to be able to select an image for download and store it locally.
I have the URL, but I don't know how to use that url in conjunction with the filepicker.
You can use the following method to download the file from a given Uri to a file selected with a file picker:
private async Task<StorageFile> SaveUriToFile(string uri)
{
var picker = new FileSavePicker();
// set appropriate file types
picker.FileTypeChoices.Add(".jpg Image", new List<string> { ".jpg" });
picker.DefaultFileExtension = ".jpg";
var file = await picker.PickSaveFileAsync();
using (var fileStream = await file.OpenStreamForWriteAsync())
{
var client = new HttpClient();
var httpStream = await client.GetStreamAsync(uri);
await httpStream.CopyToAsync(fileStream);
fileStream.Dispose();
}
return file;
}
I think you can always read the file as a stream and save it bit by bit on the local machine. But I need to say that I've done this many times in JAVA, I never needed to check this in C# :)
SaveFileDialog myFilePicker = new SaveFileDialog();
//put options here like filters or whatever
if (myFilePicker.ShowDialog() == DialogResult.OK)
{
WebClient webClient = new WebClient();
webClient.DownloadFile("http://example.com/picture.jpg", myFilePicker.SelectedFile);
}