I am trying to call a method to view a PDF
I am attempting to call the method from the URL eg. /Home.aspx/ViewPDF
The ViewPDF in the url is the method in the Home.aspx file.
I am new to ASP and this has stumped me, thanks if you can provide any help
EDIT 1:
I have an asp button with this in it's click method and it works:
protected void test12_Click(object sender, EventArgs e)
{
string FilePath = Server.MapPath("/Tasks/Content/54874/dummy.pdf");
WebClient User = new WebClient();
Byte[] FileBuffer = User.DownloadData(FilePath);
if (FileBuffer != null)
{
Response.ContentType = "application/pdf";
Response.AddHeader("content-length", FileBuffer.Length.ToString());
Response.BinaryWrite(FileBuffer);
}
}
How would I be able to make the same thing happen from visiting /Home.aspx/ViewPDF
with /ViewPDF being a method inside the code behind of Home.aspx
I believe the method needs to be static to be able to view it from the url is there any alternative for defining the file path as Server.MapPath is not static.
I have made a test method in Home.aspx:
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public static string test(object sender, EventArgs e)
{
return "test";
}
But when I visit /Home.aspx/test it just loads a version of the page with no images and slightly off css
Thanks for any help
Edit 2 / Solution:
After doing a bit of looking around on google you can easily implement MVC into web forms
https://www.davepaquette.com/archive/2013/12/30/so-you-inherited-an-asp-net-web-forms-application.aspx
From that I made a controller
public FileResult GetTaskAttatchment()
{
string ReportURL = Server.MapPath("/Tasks/Content/54874/dummy.pdf");
byte[] FileBytes = System.IO.File.ReadAllBytes(ReportURL);
return File(FileBytes, "application/pdf");
}
Which now works perfectly, Thanks again for all the help
//check your datatype for attachment shuld be varbinary...
protected void btnfinalupload_Click(object sender, EventArgs e)
{
string filename = "";
string filenameret = "";
using (DataSet ds = GetFormForDownload(id,finid))
{
if (ds.Tables[0].Rows.Count > 0)
{
filenameret = ds.Tables[0].Rows[0]["attachment"].ToString().Trim();
filename = ds.Tables[0].Rows[0]["filename"].ToString().Trim();
byte[] bytes;
string fileName, contentType;
bytes = (byte[])ds.Tables[0].Rows[0]["attachment"];
contentType = "application/pdf";
fileName = filename;
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = contentType;
Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
}
}
}
Related
I have a problem with not getting a postback after Response.End();
So the scenario is that i will click a button, clean an xmlfile and generate a message (out msg), download the xml, and then show the message in a label on the webpage. The problem is that it doesn't do anything after Response.End().
protected void btnDoIt_Click(object sender, EventArgs e)
{
string xml = "exampleXml";
string fileName = "exampleName";
MemoryStream ms = new MemoryStream();
string msg;
var cleanXml = CleanXml(xml, out msg);
cleanXml.Save(ms);
byte[] bytes = ms.ToArray();
Response.Clear();
Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}.xml", fileName));
Response.ContentType = "text/xml";
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
lblFeedback.Text = msg;
lblFeedback.Visible = true;
}
I tried moving the code in front of response.End(), like below, but it didn't work as well for some reason.
protected void btnDoIt_Click(object sender, EventArgs e)
{
string xml = "exampleXml";
string fileName = "exampleName";
MemoryStream ms = new MemoryStream();
string msg;
var cleanXml = CleanXml(xml, out msg);
lblFeedback.Text = msg;
lblFeedback.Visible = true;
cleanXml.Save(ms);
byte[] bytes = ms.ToArray();
Response.Clear();
Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}.xml", fileName));
Response.ContentType = "text/xml";
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
}
I also tried to "Click" an invisible button to get the postback like below. Didn't work either.
protected void btnDoIt_Click(object sender, EventArgs e)
{
string xml = "exampleXml";
string fileName = "exampleName";
MemoryStream ms = new MemoryStream();
string msg;
var cleanXml = CleanXml(xml, out msg);
InvisibleButtonClick(msg)
cleanXml.Save(ms);
byte[] bytes = ms.ToArray();
Response.Clear();
Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}.xml", fileName));
Response.ContentType = "text/xml";
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
}
private void InvisibleButtonClick(string msg)
{
lblXmlFeedback.Text = msg;
lblXmlFeedback.Visible = true;
InvisibleButton_OnClick(new object(), new EventArgs());
}
protected void InvisibleButton_OnClick(object sender, EventArgs e)
{
}
What am i missing here?
What you do not have understand is that the return from IIS to the browser can be one stream only.
In your case, you believe that you can send two.
What is actually happened?
A. You post back some data from the web page.
B. You return some file for download from the user.
C. There the stream end and close – nothing is going to the browser any more. So there is no way the page to refress, and there is no way the data on the page to change because you send nothing any more to the page.
How to solve this.
a) You can make a handler that download the file and you only give a link in the page, a link to the handler that download the data.
b) you can make some other page that you redirect him with the message that you like to send, and there automatically with some javascript you start downloading your file.
c) you can use ajax to download your extra data, and javascript to show any message
similar answers
What is the best way to download file from server
file download by calling .ashx page
Updating a page before initiating a download?
I have been trying to write a code to download file from the server, the path is correct but the file isn't downloading when I click it.
The delete code works properly which looks like this:
protected void DeleteFile(object sender, EventArgs e)
{
string filePath = (sender as LinkButton).CommandArgument;
File.Delete(filePath);
GenerateDownloadLinks();
}
However the download isn't starting the download (debugging runs through entire code):
protected void ButtonDownload_Click(object sender, EventArgs e)
{
string path = (sender as LinkButton).CommandArgument;
string name = Path.GetFileName(path);
string ext = Path.GetExtension(path);
HttpResponse response = HttpContext.Current.Response;
response.ClearContent();
response.Clear();
response.AddHeader("content-disposition",
"attachment; filename=" + name);
response.ContentType = "text/plain";
response.TransmitFile(path);
response.Flush();
response.End();
}
The file I am downloading is a .dat file. I tried changing and adding the configurations but with no luck
Problem was update panel related, my datalist was inside an update panel
I have an asp.net button which calls this method.
protected void DownloadFile(object sender, EventArgs e)
{
Response.Clear();
string filePath = getFilePath();
Response.ContentType = "application/vnd.ms-excel";
Response.AppendHeader("Content-Disposition", "attachment; filename=FvGReport.xlsx");
Response.TransmitFile(filePath);
Response.End();
newReportMessage.Visible = false;
}
But the newReportMessage.Visible component is never able to run. Through reading around I could see that Response.End() just terminates the thread and so that made sense. So I have tried what seems to work for a lot of other people.
protected void DownloadFile(object sender, EventArgs e)
{
Response.Clear();
string filePath = getFilePath();
Response.ContentType = "application/vnd.ms-excel";
Response.AppendHeader("Content-Disposition", "attachment; filename=FvGReport.xlsx");
Response.TransmitFile(filePath);
Response.Flush();
Response.SuppressContent = true;
HttpContext.Current.ApplicationInstance.CompleteRequest();
newReportMessage.Visible = false;
}
But it still doesn't work? Does anyone know what the problem is so I can avoid this in the future, and what is the solution?
From a file .aspx I need to have a redirect to a webpage, open it then download a file. Following my code:
page Source.aspx
<script runat="server">
protected override void OnLoad(EventArgs e)
{
Response.Redirect("Dest.aspx?download=true");
base.OnLoad(e);
}
</script>
page Dest.aspx
<script runat="server">
private void Page_Load(object sender, System.EventArgs e)
{
string download= (string)Request.QueryString["download"];
if (download == "true")
{
string url = "myurl/myfile.exe";
System.Net.HttpWebRequest objRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
System.Net.HttpWebResponse objResponse = (System.Net.HttpWebResponse)objRequest.GetResponse();
int bufferSize = 1;
Response.ClearHeaders();
Response.ClearContent();
Response.AppendHeader("content-disposition:", #"attachment;filename=""myFileName.exe""");
Response.AppendHeader("Content-Length", objResponse.ContentLength.ToString());
Response.ContentType = "application/download";
byte[] byteBuffer = new byte[bufferSize + 1];
System.IO.MemoryStream memStrm = new System.IO.MemoryStream(byteBuffer, true);
System.IO.Stream strm = objRequest.GetResponse().GetResponseStream();
byte[] bytes = new byte[bufferSize + 1];
while (strm.Read(byteBuffer, 0, byteBuffer.Length) > 0)
{
Response.BinaryWrite(memStrm.ToArray());
Response.Flush();
}
Response.Close();
Response.End();
memStrm.Close();
memStrm.Dispose();
strm.Dispose();
}
}
</script>
Two problems now:
Calling the page "Source.aspx" the download is automacally started but the page Dest.aspx is not shown in the browser
The downloaded file is called "Dest.aspx" instead of "myFileName.exe" ads I've set with
Response.AppendHeader("content-disposition:", #"attachment;filename=""myFileName.exe""");
For your second problem Issue Try something like that
string attachment = string.Format(CultureInfo.InvariantCulture, "attachment; filename=" + sfilename + "", fi.Name);
Response.ContentType = "application/octet-stream";
Response.AppendHeader("Content-Disposition", attachment);
Hope it works for you.
RIght, what you need to be doing is split the process in two:
Display your page and set a redirect value in the header to automatically redirect to your download.
download your file.
the important thing to note is that you can either respond with a web page, OR with a file, not both at once.
I want to create a download and install ipa file automatically function in to iphone/ipad in C# ?But i have no idea how to do it.I only use a command way to download the file but it wont install into my iphone/ipad automatically?Is that possible do in C#?
It wrong code just an ideal for it:
protected void Page_Load(object sender, EventArgs e)
{
string filePath = string.Empty;
string appType = string.Empty;
//ios
filePath = "appFile/Apps.ipa";
appType = "application/octet-stream";
Response.ClearContent();
Response.ContentType = MimeType(Path.GetExtension(fName),appType);
Response.AddHeader("Content-Disposition", string.Format("attachment; filename = {0}",System.IO.Path.GetFileName(fName)));
Response.AddHeader("Content-Length", sz.ToString("F0"));
Response.TransmitFile(fName);
Response.End();
}
public static string MimeType(string Extension,string appMineType)
{
string mime = appMineType;
if (string.IsNullOrEmpty(Extension))
return mime;
string ext = Extension.ToLower();
Microsoft.Win32.RegistryKey rk = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext);
if (rk != null && rk.GetValue("Content Type") != null)
mime = rk.GetValue("Content Type").ToString();
return mime;
}