ASP Downloading file using TransmitFile() - c#

I am using Response.TransmitFile() to download a zip folder from a folder on my C drive. The folder downloads fine and i get the files turn up in my downloads folder. However the problem is in my downloads folder, with a zip file that has the name of the asp page, and inside is the folder that i wanted to download. The other problem is i append a DataTime on the end of the zip folder in the upload, but the date is not on the end of the folder name either.
My Upload Code looks like this:
string pnq = HttpContext.Current.Request.Url.PathAndQuery;
string url = HttpContext.Current.Request.Url.AbsoluteUri.Replace(pnq, "/");
if (FileUpload1.HasFile)
{
var filename = FileUpload1.PostedFile.FileName;
var uriID = Guid.NewGuid().ToString();
var password = System.Web.Security.Membership.GeneratePassword(7, 2);
filename = filename.Remove(filename.Count() - 4) + "-" + DateTime.Now.ToShortDateString() + ".zip";
filename = filename.Replace(" ", "-");
filename = filename.Replace("/", "-");
FileUpload1.SaveAs("C:\\Uploads\\" + filename);
lblUri.Text = url + "UICDownload.aspx?fileID=" + uriID;
lblPassword.Text = password;
string file = MapPath("~/Sample.xml");
XDocument doc = XDocument.Load(file);
doc.Root.Add(new XElement("File", new XElement("name", filename), new XElement("uriID", uriID), new XElement("password", password)));
XElement name = new XElement("name", filename);
doc.Save(file);
}
My Download Code looks like this:
var text = Request.QueryString["fileID"];
string file = MapPath("~/Sample.xml");
XDocument doc = XDocument.Load(file);
var node = doc.Document.Descendants("uriID").FirstOrDefault(u => u.Value.Equals(text));
var filenode = node.Ancestors("File").First();
var tempname = filenode.Element("name");
var filename = tempname.Value.ToString();
var filePassword = filenode.Element("password");
if (filePassword.Value.ToString() == tbPassword.Text)
{
Response.Clear();
Response.ContentType = "application/zip";
Response.AppendHeader("Content-Disposition", "attachment; fileID=" + text);
Response.TransmitFile("C:\\Uploads\\" + filename);
Response.End();
}
The XML Document im saving to looks like this:
<?xml version="1.0" encoding="utf-8"?>
<rootElement>
<File>
<name>Pictures-21-06-2013.zip</name>
<uriID>96e1253b-634b-498a-b062-61a1a097ee3f</uriID>
<password>%zFxRr|</password>
</File>
<File>
<name>Test1-21-06-2013.zip</name>
<uriID>44d3d2c8-5c19-4f79-a5e2-66bb023a4d5e</uriID>
<password>{hik6.e</password>
</File>
Please any suggestions are welcome, and let me know if you would like me to show any other code. Also just to add, when the files are uploaded into the C:\Uploads folder, the zip folders have the date at the end of their names.

Try changing this line to the following:
Response.AppendHeader("content-disposition", "attachment; filename=" + filename);

Related

.NET MVC - Generating excel file using OpenXML

I'm having a trouble with generating a .xlsx file from a template which is placed in my project resources. First I'm creating a new ExcelPackage, then opening the template which I'm going to fill with some data - but by now I want to simply download the original xlsx template. I'm trying to get the template without any modifications and download as 'Test.xlsx'. When it's downloaded, after opening the file Excel says that it cannot open my file due to invalid format or extension. Does anyone know what I am doing wrong? When I console.log my response.data then evidently there is some binary data ( about 50kb), but excel cannot show this data properly. Here is some code:
Code from .cshtml :
generateReport(){
this.#http.post(SERVER_URL + "/Mvc/Excel/GenerateReport")
.then(response => {
var blob = new Blob([response.data], { type: 'application/ms-excel' });
var downloadUrl = URL.createObjectURL(blob);
var a = document.createElement('a');
a.href = downloadUrl;
a.download = "Test.xlsx";
document.body.appendChild(a);
a.click();
});
.catch(error => {
console.log('error ', error);
return null;
});
}
Here is my controller action:
[HttpPost]
public void GenerateReport(){
string fileName;
string strfilepath = TemplatePath + "MyTemplate.xlsx";
//TemplatePath - path from my configuration where my xlsx template is stored
using(ExcelPackage p = new ExcelPackage())
{
using(FileStream = new FileStream(strfilepath, FileMode.Open))
{
p.Load(stream);
fileName = "TestReport.xlsx";
Byte[] bin = p.GetAsByteArray();
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment; filename=" + fileName);
Response.ContentType = "application/ms-excel";
Response.Charset = "";
Response.BinaryWrite(bin);
Response.Flush();
Response.End();
}
}
}
I think the content type should be application/vnd.ms-excel for exporting excel files.

Download pdf file on remote Client Machine where my publish site is running

I had publish my site and access it from remote location , but the when i download the pdf file it get downloaded and saved on server side where i published my code.
int FOrgCountRows = OrgCountRows;
string folderName = #"c:\EStatement\";
foreach (DataRow dr in DTAC.Rows)
{
if (DTAC.Rows[FOrgCountRows - OrgCountRows]["Acc"].ToString() == AccArray[CountAcc].ToString())
{
DataT.ImportRow(dr);
if((FOrgCountRows - OrgCountRows)!=( DTAC.Rows.Count)-1)
OrgCountRows--;
DTACCount++;
}
if (DTAC.Rows[FOrgCountRows - OrgCountRows]["Acc"].ToString() != AccArray[CountAcc].ToString())
{
string fileName = "_" + AccArray[CountAcc] + ".pdf";
CountAcc++;
string extension;
string encoding;
string mimeType;
string[] streams;
Warning[] warnings;
LocalReport report = new LocalReport();
report.ReportPath = Server.MapPath("~/Rpt123.rdlc");
ReportDataSource rds = new ReportDataSource();
rds.Name = "DataSet1";
rds.Value = DataT;
report.DataSources.Add(rds);
byte[] mybytes = report.Render("PDF", null, out extension, out encoding, out mimeType, out streams, out warnings); //for exporting to PDF
if (!System.IO.File.Exists(folderName))
{
using (FileStream fs = File.Create(folderName + fileName))
{
fs.Write(mybytes, 0, mybytes.Length);
}
}
else
{
Console.WriteLine("File \"{0}\" already exists.", fileName);
return;
}
Response.Buffer = true;
Response.Clear();
Response.ContentType = contentType;
Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
Response.WriteFile(folderName + fileName);
-----string folderName = #"c:\EStatement\"; this is the Target folder.. I want to download the files on client machine on this specified folder.. ANy SOLUTION?
Possible duplicate:
ASP.net download and save file in user folder
Anyway:
"
Filestream will write to a file on server and not on the client's machine.
Try writing the document bytes to response output stream and a content-disposition http header to response.
Response.AddHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
"
This would prompt user for the file download based on browser setting.
You cannot control which directory file goes in in the client's machine.

how to write an image into doc file in asp.net C# without other dll's

i am looking to write an image into doc file ..
here is the code that i am trying...
string imageFolder = System.Web.Configuration.WebConfigurationManager.AppSettings["coverLetterPath"].ToString();
string imageName = "images.jpg";
string path1 = Path.Combine(imageFolder, imageName);
// Create a file to write to.
using (StreamWriter sw = File.CreateText(path1))
{
sw.WriteLineAsync(imageName);
}
string fileName = string.Empty;
fileName = "BodyContent_" + DateTime.Now.ToString("ddMMMyyy_HHmmss_fff") + ".docx";
Response.ContentType = "application/octet-stream";
Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);
Response.TransmitFile(path1);
Response.Flush();
Response.End();
here the file that i am creating is downloaded but the image is not loaded into that file.. getting a message when i open the doc as File is corrupted

How to set the filename when uploading in asp.net

I am using the following code to upload a file and save it on the disk. The filename is like:
BodyPart4353453453
E.g. When I upload a file called alfa.txt it will be saved as BodyPart24245343.
How can I set the filename each time?
var uploadFolder = "/Content/Images/" + listingId;
var provider = GetMultipartProvider(uploadFolder);
var result = await Request.Content.ReadAsMultipartAsync(provider);
Try somthing like this.
// change file name with its extension
var fileName = Guid.NewGuid().ToString() +
System.IO.Path.GetExtension(file.FileName);
var uploadUrl = Server.MapPath("~/uploads");
file.SaveAs(Path.Combine(uploadUrl, fileName));

Download file with international characters in file name

In my application I'm uploading a file which has Swedish characters in file name. It works fine.
But when I try to download it, I get an error: "An invalid character was found in the mail header" ..Could you help regarding this
Please see my code
public ActionResult Download(Guid id)
{
var attachment = AttachmentService.GetAttachmentById(id);
var cd = new ContentDisposition
{
FileName = Utility.GetCleanedFileName(((FileAttachment)attachment).FileName),
Inline = false,
};
var file = File("\\App_Data" +((FileAttachment)attachment).FilePath, "Application");
Response.ClearHeaders();
Response.Clear();
Response.ContentType = file.ContentType;
Response.AppendHeader("Content-Disposition", cd.ToString());
var filePath = "\\App_Data" + ((FileAttachment) attachment).FilePath;
Response.WriteFile(filePath);
Response.End();
return file;
}
Please try to encode the filename using HttpUtility.UrlPathEncode.
http://msdn.microsoft.com/en-us/library/system.web.httputility.urlpathencode.aspx

Categories

Resources