i want to write a api for download all file in zipped , file path will come from database
Loading
i want to write a api for download all file in zipped , file path will come from database
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Vishal YelveRank #178 · 13.6K reputationPosted Jul 18, 2023, 2:30 AM EDT
Hi Sandeep,
Do refer below links
https://www.aspsnippets.com/Articles/Download-Compressed-Zip-File-from-Web-API-in-ASPNet-MVC.aspx
https://stackoverflow.com/questions/41383338/how-to-download-a-zipfile-from-a-dotnet-core-webapi
Sandeep KumarRank #1,642 · 937 reputationPosted Jul 19, 2023, 3:24 AM EDT
it is working https://www.aspsnippets.com/Articles/Download-Compressed-Zip-File-from-Web-API-in-ASPNet-MVC.aspx
but when i want to download from url it is not working pls guide
how can i download multiple file from url in Zip File
My Url Is like :-http://148.72.207.115:4458/BBGS_Unit3_BD_GEN_2021-2022_sample_001.png
Amit MohantyRank #112 · 20K reputationPosted Jul 19, 2023, 5:09 AM EDT
Try this
[HttpGet("{filename}")] public async Task DownloadFile(string filename) { // Replace "path/to/files" with the actual path to your files string filePath = Path.Combine("path/to/files", filename); if (!System.IO.File.Exists(filePath)) { return NotFound(); } // Generate a unique file name for the zip file string zipFileName = $"{Path.GetFileNameWithoutExtension(filename)}_{DateTime.Now:yyyyMMddHHmmss}.zip"; string zipFilePath = Path.Combine(Path.GetTempPath(), zipFileName); // Create a new zip archive using (var zipArchive = ZipFile.Open(zipFilePath, ZipArchiveMode.Create)) { // Add the file to the zip archive zipArchive.CreateEntryFromFile(filePath, Path.GetFileName(filePath)); } // Read the zip file into a byte array byte[] zipBytes = await System.IO.File.ReadAllBytesAsync(zipFilePath); // Clean up the temporary zip file System.IO.File.Delete(zipFilePath); // Set the Content-Disposition header to prompt the user to download the file var contentDisposition = new System.Net.Mime.ContentDisposition { FileName = zipFileName, Inline = false // Set this to true if you want the browser to attempt to display the file inline }; Response.Headers.Add("Content-Disposition", contentDisposition.ToString()); // Return the zip file as a byte array return File(zipBytes, "application/zip"); }Sandeep KumarRank #1,642 · 937 reputationPosted Jul 19, 2023, 6:24 AM EDT
I don;t need in mvc
It is working for local path but i want to fetch file from Url
My Url Is like :-http://148.72.207.115:4458/BBGS_Unit3_BD_GEN_2021-2022_sample_001.png
My Code is like
[Authorize]
[HttpGet]
public HttpResponseMessage DownloadImage(Int Id)
{
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK);
try
{
UserIdentity UI = new UserIdentity((ClaimsIdentity)User.Identity);
var RoleId = Convert.ToInt32(UI.RoleId);
var UserID = Convert.ToInt32(UI.UserID);
PmsInsertUpdateData _KD = new PmsInsertUpdateData();
// var CD_Dtls = _KD.GetPmsUploadedImage(Id);
DataTable DtImage = _KD.DownloadImage(jsonParam);
string filePath = string.Empty;
using (ZipFile zip = new ZipFile())
{
zip.AlternateEncodingUsage = ZipOption.AsNecessary;
zip.AddDirectoryByName("Files");
foreach (DataRow row in DtImage.Rows)
{
filePath = row["FileName"].ToString();
string localPath = new Uri(filePath).LocalPath;
zip.AddFile(filePath, "Files");
}
//Set the Name of Zip File.
string zipName = String.Format("Zip_{0}.zip", DateTime.Now.ToString("yyyy-MMM-dd-HHmmss"));
using (MemoryStream memoryStream = new MemoryStream())
{
//Save the Zip File to MemoryStream.
zip.Save(memoryStream);
//Set the Response Content.
response.Content = new ByteArrayContent(memoryStream.ToArray());
//Set the Response Content Length.
response.Content.Headers.ContentLength = memoryStream.ToArray().LongLength;
//Set the Content Disposition Header Value and FileName.
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentDisposition.FileName = zipName;
//Set the File Content Type.
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/zip");
return response;
}
}
}
catch (Exception ex)
{
response = Request.CreateResponse(JsonConvert.DeserializeObject("{\"StatusCode\":\"500\",\"ErrorMessage\":\"" + ex.Message + "\"}"));
return response;
}
// = Request.CreateResponse(HttpStatusCode.OK, response);
}
Amit MohantyRank #112 · 20K reputationPosted Jul 19, 2023, 6:38 AM EDT
Check this
[Authorize] [HttpPost] public IActionResult DownloadImage(JObject jsonParam) { try { UserIdentity UI = new UserIdentity((ClaimsIdentity)User.Identity); var RoleId = Convert.ToInt32(UI.RoleId); var UserID = Convert.ToInt32(UI.UserID); PmsInsertUpdateData _KD = new PmsInsertUpdateData(); DataTable DtImage = _KD.DownloadImage(jsonParam); string filePath = string.Empty; using (ZipFile zip = new ZipFile()) { zip.AlternateEncodingUsage = ZipOption.AsNecessary; zip.AddDirectoryByName("Files"); foreach (DataRow row in DtImage.Rows) { filePath = row["FileName"].ToString(); string localPath = new Uri(filePath).LocalPath; zip.AddFile(filePath, "Files"); } // Set the Name of the ZIP File. string zipName = String.Format("Zip_{0}.zip", DateTime.Now.ToString("yyyy-MMM-dd-HHmmss")); using (MemoryStream memoryStream = new MemoryStream()) { zip.Save(memoryStream); return File(memoryStream.ToArray(), "application/zip", zipName); } } } catch (Exception ex) { return BadRequest(ex.Message); } }Sandeep KumarRank #1,642 · 937 reputationPosted Jul 19, 2023, 6:56 AM EDT
Error :showing
{
"StatusCode": "500",
"ErrorMessage": "URI formats are not supported."
}
Actually I want to retreive file from live url
l like :-http://148.72.207.115:4458/BBGS_Unit3_BD_GEN_2021-2022_sample_001.png
Pls Go through my code .i don't want in mvc ,i want normal web api
Sandeep KumarRank #1,642 · 937 reputationPosted Jul 19, 2023, 7:08 AM EDT
Please i dont't want in mvc
I want Normal aso.net web api
Pls go through my code
[Authorize]
[HttpPost]
public HttpResponseMessage DownloadImage(JObject jsonParam)
{
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK);
try
{
UserIdentity UI = new UserIdentity((ClaimsIdentity)User.Identity);
var RoleId = Convert.ToInt32(UI.RoleId);
var UserID = Convert.ToInt32(UI.UserID);
PmsInsertUpdateData _KD = new PmsInsertUpdateData();
// var CD_Dtls = _KD.GetPmsUploadedImage(jsonParam);
DataTable DtImage = _KD.DownloadImage(jsonParam);
string filePath = string.Empty;
using (ZipFile zip = new ZipFile())
{
zip.AlternateEncodingUsage = ZipOption.AsNecessary;
zip.AddDirectoryByName("Files");
foreach (DataRow row in DtImage.Rows)
{
filePath = row["FileName"].ToString();
string localPath = new Uri(filePath).LocalPath;
zip.AddFile(filePath, "Files");
}
//Set the Name of Zip File.
string zipName = String.Format("Zip_{0}.zip", DateTime.Now.ToString("yyyy-MMM-dd-HHmmss"));
using (MemoryStream memoryStream = new MemoryStream())
{
//Save the Zip File to MemoryStream.
zip.Save(memoryStream);
//Set the Response Content.
response.Content = new ByteArrayContent(memoryStream.ToArray());
//Set the Response Content Length.
response.Content.Headers.ContentLength = memoryStream.ToArray().LongLength;
//Set the Content Disposition Header Value and FileName.
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentDisposition.FileName = zipName;
//Set the File Content Type.
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/zip");
return response;
}
}
}
catch (Exception ex)
{
response = Request.CreateResponse(JsonConvert.DeserializeObject("{\"StatusCode\":\"500\",\"ErrorMessage\":\"" + ex.Message + "\"}"));
return response;
}
// = Request.CreateResponse(HttpStatusCode.OK, response);
}
Amit MohantyRank #112 · 20K reputationPosted Jul 19, 2023, 7:14 AM EDT
foreach (DataRow row in DtImage.Rows) { filePath = row["FileName"].ToString(); string localPath = new Uri(filePath).LocalPath; zip.AddFile(filePath, "Files"); }Change the above code with below code and try again:
using (HttpClient client = new HttpClient()) { foreach (DataRow row in DtImage.Rows) { string fileUrl = row["FileUrl"].ToString(); string fileName = Path.GetFileName(fileUrl); byte[] fileBytes = client.GetByteArrayAsync(fileUrl); zip.AddEntry(fileName, fileBytes); } }Sandeep KumarRank #1,642 · 937 reputationPosted Jul 19, 2023, 7:18 AM EDT
Error showing
Amit MohantyRank #112 · 20K reputationPosted Jul 19, 2023, 7:38 AM EDT
Use client.GetByteArrayAsync(fileUrl)
using (HttpClient client = new HttpClient()) { foreach (DataRow row in DtImage.Rows) { string fileUrl = row["FileUrl"].ToString(); string fileName = Path.GetFileName(fileUrl); byte[] fileBytes = client.GetByteArrayAsync(fileUrl); zip.AddEntry(fileName, fileBytes); } }Sandeep KumarRank #1,642 · 937 reputationPosted Jul 19, 2023, 7:43 AM EDT
still error showing