How to download file and reload - asp.net

I have a page which contains a button that perform the following code, I want to reload the page after the response end so that update a grid in that page. or suggest a way to update the grid after response end.
string report = new BLL.OrderReport.OrderReport().GenerateFullfilmentReport(fromdate, toDate
, string.IsNullOrEmpty(generationId)? null : ((int?)int.Parse(generationId)) );
if (!string.IsNullOrEmpty(report))
{
LoadReportHistory();
Response.ContentType = "text/plain";
Response.AppendHeader("Content-Disposition", "attachment; filename=Report.text");
Response.Write(report);
Response.End();
}
Thanks

I work around this, the problem is that I need the Grid to be rebind after Response.End is called.
The target is updating the Grid when user click download. To work this out I rebind the grid first, and register a java script code to cause reloading the page (post back event will be resent),
in the second round I download the file.
I control this miss by copying the original file to temp file, then delete the temp file during first round, if the file exist then download.
Someone tell me something better please

Related

Access request after upload (ASP classic)

So, as I figured out, when I have a form with enctype="multipart/form-data" and I upload a file, I can no longer access the object request. The following error is shown:
Cannot use the generic Request collection after calling BinaryRead.
After checking some resources, I stumpled upon a statement, which says: "This is by design". Well, okay, not here to judge about design-decisions.
To give you a quick overview, let me walk you through the code:
if request("todo") = "add" then
Set Form = New ASPForm
category = request("category")
title = request("title")
if len(Form("upload_file").FileName) > 0 then
filename = Form("upload_file").FileName
DestinationPath = Server.mapPath("personal/allrounder/dokumente/")
Form.Files.Save DestinationPath
end if
end if
Nothing too special here so far. Later however, when I try to access my request object, the error mentioned above occures:
<% if request("todo") = "new" then %>
...
My question now, how to get rid of it or fix this. I don't want to open the upload in a popup if there is another way around. This is the only solution I could think off.
Perfectly would be an object, which checks Form and request. Alternatively maybe a check at the top of the file, which object I have to use?
Thanks for any suggestions.
There used to be a very popular ASP class/component that solved ASP file uploads. The site for that component has been taken down, but the code is mirrored here:
https://github.com/romuloalves/free-asp-upload
You can include this ASP page on your own page, and on your page instantiate the class to get access to the files in your form, but also to the form variables. Here is a piece of example code (Upload.Form accesses the form fields):
Dim uploadsDir : uploadsDir = server.mapPath(".") ' whatever you want
Dim Upload, ks, fileKey, mailto
Set Upload = New FreeASPUpload
call Upload.Save(uploadsDir)
ks = Upload.UploadedFiles.keys
for each fileKey in ks
Response.write(fileKey & " : " & Upload.UploadedFiles(fileKey).FileName & "<br/>")
next
mailto = Upload.form("mailTo")
Set Upload = Nothing
If you want to stick to your own implementation, you can probably figure out how to get to the form variables in a multipart/form-data encoded data stream by having a look at the code they use to do so.

JSF - Trying to download a PDF file but it rerenders the page with strange characters [duplicate]

everyone!
I have a trouble. I tried to save excel file in jsf web application.
I generated file by my utils and trying to get "save" window, but I failed.
Here is my code:
<div>
<h:commandButton value="Apply" actionListener="#{hornPhonesBean.generateReport}"/>
</div>
and:
public void generateReport(ActionEvent event) {
System.out.println("GENERATE REPORT FROM = " + this.dateFrom + "; TO = " + this.dateTo);
try {
XSSFWorkbook workbook = (XSSFWorkbook) HornReportGenerator.getWorkbook(null, null);
String fileName = "1.xlsx";
FacesContext fc = FacesContext.getCurrentInstance();
ExternalContext ec = fc.getExternalContext();
// Some JSF component library or some Filter might have set some headers in the buffer beforehand. We want to get rid of them, else it may collide.
ec.responseReset();
// Check http://www.w3schools.com/media/media_mimeref.asp for all types. Use if necessary ExternalContext#getMimeType() for auto-detection based on filename.
ec.setResponseContentType("application/vnd.ms-excel");
// Set it with the file size. This header is optional. It will work if it's omitted, but the download progress will be unknown.
//ec.setResponseContentLength(contentLength);
// The Save As popup magic is done here. You can give it any file name you want, this only won't work in MSIE, it will use current request URL as file name instead.
ec.setResponseHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
OutputStream output = ec.getResponseOutputStream();
workbook.write(output);
output.flush();
output.close();
fc.responseComplete(); // Important! Otherwise JSF will attempt to render the response which obviously will fail since it's already written with a file and closed.
System.out.println("END");
} catch (Exception e) {
e.printStackTrace();
}
}
I read suggestions here and from another forums - everyone says I shouldnt use , but I didn't use it at all.
Then I thought that the problem could be in the
<ice:form>,
where I kept the
<h:commandButton>,
and I changed to
<h:form>,
but it didn't help.
Maybe the problem in the request - it has header Faces-Request partial/ajax. But I am not sure.
Please give me some ideas - I already spent 4 hours for this crazy jsf download issue)
Maybe the problem in the request - it has header Faces-Request partial/ajax. But I am not sure.
This suggests that the request is an ajax request. You can't download files by ajax. Ajax requests are processed by JavaScript which has for obvious security reasons no facilities to programmatically pop a Save As dialogue nor to access/manipulate client's disk file system.
Your code snippet does however not show that you're using ajax. Perhaps you oversimplified it too much or you're using ICEfaces which silently auto-enables ajax on all standard JSF command components.
In any case, you need to make sure that it's not sending an ajax request.
See also:
How to provide a file download from a JSF backing bean?
ICEfaces libary in classpath prevents Save As dialog from popping up on file download

asp.net reload page after export to excel

I have a page which exports a document to excel on button click. What I need to do is refresh the page after the excel document has been sent.
I am trying to register a script which will cause a page refresh but cant get it to register at the same time as exporting to excel.
ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), "test", "alert('Done');", True)
Response.Clear()
Response.ClearHeaders()
Response.AddHeader("Refresh", "3; url=" + Request.RawUrl)
Response.ContentType = strMimeType
Response.AddHeader("content-disposition", "attachment; filename=CompleteReport." + strFilenameExtension)
Response.BinaryWrite(bytFileContent)
Response.End()
You can make
only one response for each requests
(first excel export, and the second would be the refresh).
After first response.end, you can't do anything.
You have to solve the excel export another way, with component etc.
And after export you can call
Response.redirect("your page");
Basically this can not be done if you want it reloaded only after the file has downloaded as it it not possible to find out when that is. Also you are clearing the response out and then writing the excel so the script isn't even returned from the server. The refresh-header is not being used by the browser when downloading a file either.
What you can do is to use the aspx-page to include a script like:
function onclick() {
window.location.href = 'loadmyfile.ashx?parameters...';
refreshPage();
}
The above will however refresh the page immediately on click so that might not be what you are after.

PDF from content of asp.net page

I'm trying to create a pdf of the content on a page ("returnsPage.aspx?id="returnId) and allow the user to download this directly when clicking the button.
However in my onClick method I have the following code:
lnkLoadPDF.CommandArgument = "/returns/returnsPage.aspx?id="+returnId.ToString();
string virtualPath = lnkLoadPDF.CommandArgument;
string fileName = System.IO.Path.GetFileName(virtualPath);
Response.Clear();
Response.AddHeader("content-disposition", "attachment; filename=" + fileName);
Response.WriteFile(virtualPath);
Response.ContentType = "";
Response.End();
Response.Redirect("/returns/returnsPage.aspx?id="+returnId);
which returns this error:
'/returns/returnsPage.aspx?id=23' is not a valid virtual path.
Can anyone please tell me what I'm doing wrong?
Thanks!
In order to turn a webpage into a pdf, you must convert it to pdf on the server. In order to do that, you must have a program on the server that can do that for you.
I've tried a variety of webpage-to-pdf converters and one of the better ones is a free, open source program called wkhtmltopdf.
After you create the pdf, you can either redirect the user to the newly created pdf (discouraged), or prompt them to download it with a savefile dialog.
If you get stuck, just search for wkhtmltopdf on stackoverflow or post another question.
You can't send a file to the client and redirect him to a new location during the same request. You also can't create a PDF from a webpage without some kind of component that converts the HTML into a PDF, it's (quite a bit) more tricky that what I think you're trying to attempt.
As for your exception, are you sure returnsPage.aspx exists? :)

How to designate the name of a file that a user downloads via an ASHX downloader?

This is my first time writing code that allows a user to download a file uploaded by another user.
I've written an ASHX file, download.ashx, with code that looks like this:
s = context.Request.QueryString.ToString();
byte[] buffer = new ReplacementTicketFileIO().GetSpecifiedFile(s);
context.Response.BinaryWrite(buffer);
context.Response.Flush();
context.Response.End();
When a user clicks on a link to download.ashx with the appropriate querystring, the file is downloaded, but the browser wants to display the content in the browser window. If the user right-clicks on the link, he can download the file, but the name of the file defaults to download.ashx.
I would like to accomplish two things:
1) I would like to be able to specify the default name of the file downloaded on the user's device based on the querystring.
For instance, if the user clicks on download.ashx?linkedfile=car.pdf, I would like for the browser to default to car.pdf for the name of this file.
2) I would like for the browser to default to saving the link, as opposed to opening the link in the browser window.
Is it reasonable for me to want to do this, or is there a better way to download files? Please let me know.
Set the Content-Disposition HTTP header. E.g.
Content-Disposition: attachment; filename=hello.jpg
You can do that in C# using:
Response.AddHeader("Content-Disposition", "attachment; filename=hello.jpg");
Here is something I have for excel files and I believe it forces a download rather than a new window. There is a page property for QueryString. You would just need to capture the QueryString and use it in this code as well as determining the content type. The String.Format will give you clean code.
private string _ExcelFilename
{
get
{
return (Request.QueryString["xls"] != null) ? Request.QueryString"xls"] : "bis";
}
}
Page.Response.Clear();
Page.EnableViewState = false;
Page.Response.Clear();
Page.Response.ContentType = "application/vnd.ms-excel";
Page.Response.AppendHeader("Content-Disposition", String.Format("attachment; filename={0}_{1}.xls", _ExcelFilename, DateTime.Now.ToString("yyyyMMdd")));
Page.Response.Write(excel);
Page.Response.Flush();
Page.Response.End();

Resources