Rectangle 27 1

The element that was calling this was an anchor tag that would call this then download an exe file and when the file download dialog box poped up it would cancel this request as if it were navigating to a new page.

function download(fileid, href)
    $.post("download.php", {task: "download", fileid: fileid}, function(data){
        window.location.href = href;

<a onclick="download(1, file.exe);return false;" href="file.exe">Download</a>

jquery ajax error {"readyState":0,"responseText":"","status":0,"status...

jquery ajax
Rectangle 27 14

You have to make a regular Servlet, you cannot stream binary data from ReportsServiceImpl. Also, there is no way to call the servlet from ReportsServiceImpl - your client code has to directly invoke the servlet.

On the client side, you'd have to create a normal anchor link with the parameters passed via the query string. Something like <a href=""</a>.

On the server side, move your code to a standard Servlet, one that does NOT inherit from RemoteServiceServlet. Read the parameters from the request object, create the excel and send it back to the client. The browser will automatically popup the file download dialog box.

java - Download dynamic file with GWT - Stack Overflow

java gwt servlets rpc
Rectangle 27 1

What you are trying is slightly complex. Not the First part but the Second part.

PART 1) Click the "Summary Download" button to launch the "File Download" dialog

PART 2) Click the Save button in the "File Download" to finally save the file

Place a WebBrowser1 Control and a Button on your form. Paste this code.

Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
End Sub

Private Sub WebBrowser1_DocumentCompleted(sender As Object, e As  _
System.Windows.Forms.WebBrowserDocumentCompletedEventArgs) Handles WebBrowser1.DocumentCompleted

    If WebBrowser1.ReadyState <> 4 Then Exit Sub

    Dim el As HtmlElement = _

End Sub

Now when you run this code, it will Click on the button "Summary Download" and launch the File Download Dialog box. See snapshot below.

PART 2 - The complex Part

Now you need to use API's to click on the Save button on the File Download dialog box. Fortunately, I have covered this in my blog so you won't have any problems :)

Topic: VBA/VB.Net/VB6Click Open/Save/Cancel Button on IE Download window PART I

Ah! But, that is really not what I wanted. The deal is, I am setting this up as a cron job to run every 30 minutes on windows task scheduler. So, I cannot do it from my own form. What I was trying to achieve was from within IE itself. Here is my code (and of course it does not work) Dim ie as object ie = CreateObject("InternetExplorer.Application") ie.visible = True ie.navigate(strURL) Do Until ie.ReadyState = "READYSTATE_COMPLETE" Loop ie.document.forms(1).submit() ie.Document.all("ctl00$WebSplitter1$tmpl1$ContentPlaceHolder1$sumBtnDownload").Click()

You can still create an exe and instead of calling it from the button, call it from the form load event :) That ways it will work with windows task scheduler.

Another way would be to go about writing a console application and using the above code :)

It never seems to get into the Webbrowser1 code. I did make sure it was called Webbrowser1. When I click the button it loads the page fine and then it exits the code. - Excel Download from page - Stack Overflow excel download
Rectangle 27 1

Ok, first thing first, the browser need to know the file location to download it. Anyone opening a standard browser dev tool like Firebug will be able to see in plain text the URL of your file.

Now, I suppose you want to protect your file from unauthorised download. If that is what you want, there is a way for that using session.

On your first page, you will put your code to check if the download is authorized. You will then put in session the current with something that identify the file. Anything that is unique for the file will do, like the database id.

$_SESSION['download_key'] = time();

Then, you redirect to a page with a html meta like this

<meta http-equiv="refresh" content="5;/download.php?file=download_key" />

This is the page where you will say "Thank you fine lad for downloading my awesome file". Note that you can also put the content of the "content" attribute in a header file if you like, like this

header('Refresh: 5;/download.php?file=download_key');

Note that the 5 is the number of second until the download file dialog box appear.

Then on download.php you will do the following :

1- Check which file was requested using the $_GET['file'].

2- Then you check if the download_key exists in session. If not, you exit the script like that

if (!isset($_SESSION['download_key'])) die('Unauthorized');

3- Then you check if the timestamps is older than some arbitrary time limit. Here with 30 sec

if ($_SESSION['download_key'] - time() > 30) die('Unauthorized');

4- Finally, if all check out, you send the file like that

header('Content-disposition: attachment; filename=myfile.ext');
header('Content-type: bin/x-file-type'); //Change for the correct mimetype

After the readfile, you will put the code to set the download to 1 in the database.

And that's it, protected file download, and anybody using the URL directly will be greeted by a big "unauthorized" text.

I'd also like to add that if you have a big file (more than say a few kilobyte), you may be better off disabling output buffering, since that will mean that php will keep a copy of the file in memory for the whole duration of the download. With the readfile function, php will send it to the browser as it read it on the disk and thus will use less memory (and will start to send data sooner).

EDIT : What make it work is the following

I actually inverted the sequence : the visitor is first redirected to the thank you page which contain a Refresh header/tag. The magic of the Refresh header is that it redirect AFTER the content is loaded. Once on the thank you page, the browser seeing that header then wait for the specified time while showing the page, then redirect to the download. Once redirected, the browser see that its a file to be downloaded and instead of changing the page, just show the download file dialog. Once the user click OK, the download will start but he will stay on the same page.

In a nutshell, you don't need to redirect after the file download, since you are already on the thank you page! I don't think it's even possible to redirect after a file download. Just look at what happen when you click on a link that point to a direct file on the webserver. The browser prompt for download, but does not cut your navigation. Once the download is started, you can happily click away from the page with the link. By the time the download is over, you may be on a completely different Website. That is why you can only show the thank you page before. But if you put a zero for the refresh header/tag, the download prompt will appear as soon as the page is loaded, so it's almost as if the two were simultaneous (in the eye of the visitor)

Thanks for that, there's a lot in there to help me refine what I've got. However, what I don't understand is what happens when you get to this download page. Because you can't echo anything before the header and you can't echo anything after the header as it is read as part of the file, how can you redirect/link the user back to a page of any substance without them using the back arrow!

Thanks Laurent - that's exactly the way I've gone with now. DOing it in reverse and just getting the scrip to change the header rather than the actual page. And thanks for the tip about ob-flush with big files - hadn't thought of that!

Force download with PHP then redirect - Stack Overflow

php redirect header download hide
Rectangle 27 16

If you mean letting the user click a link and have a dialog box pop up to save certain content as a text file:

$download_me = "download me...";
header("Content-type: text/plain");
header("Content-Disposition: attachment; filename=test.txt");
echo $download_me;

Is that what you're aiming at? Also, you might want to write a few lines that only allows the headers to be sent this way if a certain $_POST or $_GET variable is set.

you add the headers than echo. test.txt is the filename the user sees, not a file on the server

Thanks for clarifying that for me Sam. @facha - make sure to accept and close the post out :)

php: download variable content as file - Stack Overflow

php file download attachment
Rectangle 27 14

In our current project at work we had a invisible iFrame and I had to feed the url for the file to the iFrame to get a download dialog box. On the button click, the controller generates the dynamic url and triggers a $scope event where a custom directive I wrote, is listing. The directive will append a iFrame to the body if it does not exist already and sets the url attribute on it.

EDIT: Adding a directive

appModule.directive('fileDownload', function ($compile) {
    var fd = {
        restrict: 'A',
        link: function (scope, iElement, iAttrs) {

            scope.$on("downloadFile", function (e, url) {
                var iFrame = iElement.find("iframe");
                if (!(iFrame && iFrame.length > 0)) {
                    iFrame = $("<iframe style='position:fixed;display:none;top:-1px;left:-1px;'/>");

                iFrame.attr("src", url);


    return fd;

This directive responds to a controller event called downloadFile

so in your controller you do

$scope.$broadcast("downloadFile", url);

Code snippet would be a great help.

The directive above is not working for me, when I put iframe creation outside scope.$on it creates iframe but $on event is not calling when using broadcast

Yes $scope.$broadcast works only on children. You can put the directive on the top level scope if possible.

How do you serve a file for download with AngularJS or Javascript? - S...

javascript angularjs
Rectangle 27 1

Well I have found atleast a temporary fix for the problem. All my links for force downloads were target _blank..once I created standard non pop out links the file downloads worked in IE. There is probably some type of work around but I just also realized there is really no need for a pop up window for the download anyway..the download dialog box already serves that purpose.

You should clean this answer up and mark it as the accepted answer so people who come across this question in the future know how you solved it.

php - Codeigniter Force download IE - Stack Overflow

php pdf codeigniter force-download
Rectangle 27 1

Private Declare Function URLDownloadToFile Lib "urlmon" Alias _
"URLDownloadToFileA" (ByVal pCaller As Long, ByVal szURL As String, _
ByVal szFileName As String, ByVal dwReserved As Long, ByVal lpfnCB As Long) As Long

Sub DownloadFileFromWeb()

    Dim myFile As String
    Dim buf, Ret As Long
    Dim strSavePath As String
    Dim URL As String, ext As String

    URL = ""         
    buf = Split(URL, ".")
    ext = buf(UBound(buf))

    strSavePath = "C:\local files\DownloadedFile." & ext
    Debug.Print strSavePath

    Ret = URLDownloadToFile(0, URL, strSavePath, 0, 0)

    If Ret = 0 Then
        MsgBox "Download OK!"
        MsgBox "Error"
    End If

End Sub

Difficulites in accessing the Download files dialog box - VBA Code - S...

Rectangle 27 1

Sorry, my rep isn't high enough to leave a comment, so this isn't an answer; it's a question/suggestion... I wanted to ask if you are trying to get the program to download the file automatically, or if by "stuck" you are saying that the dialog box that comes up with the open/save buttons doesn't allow you to proceed; i.e., you can't actually click the open/save buttons? The reason I ask is that I imagine it would be more efficient if the url is always the same to just download the file through vba without using the dialog box at all.

By stuck I mean I cant figure out the code that would allow me to click the open or save command in vba. I am physically able to click the buttons manually.

I'm not sure about your options with a web form... With standard in-workbook user forms, you can just use something like: UserForm1.CommandButton1_Click, though normally in code, you bypass the need for clicking on something or selecting/activating anything by just having the code do the job that the button would have done.

However, if you really do need to click that button for some reason, rather than just performing the download through the code, you might be able to get away with some Send Keys commands that move your cursor/selection to the button you want clicked and press enter. I suggest staying far away from Send Keys if at all possible though...

excel - VBA code brings up dialog box with open or save options but I ...

excel vba internet-explorer download
Rectangle 27 1

#Start IE and navigate to your download file/location
$ie = New-Object -Com internetExplorer.Application

#Wait for Download Dialog box to pop up
Sleep 5
while($ie.Busy){Sleep 1} 

#Hit "S" on the keyboard to hit the "Save" button on the download box
$obj = new-object -com WScript.Shell
$obj.AppActivate('Internet Explorer')

#Hit "Enter" to save the file

#Closes IE Downloads window

internet explorer - Automating Saving a file from the web with the IE ...

internet-explorer powershell com
Rectangle 27 1

hi nader ,i have tried this code.i got an exception on response.Flush(); "[System.Threading.ThreadAbortException] = {Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack.}" and the file is downloaded normally without open save as dialog box

c# - Save As Dialog box in - Stack Overflow

c# browser savefiledialog
Rectangle 27 2

If what you are trying to do is when they click on the file download link it pops up with save as or open dialog box, this is to do with the user's browser configuration. In the case of PDF's i believe Firefox has open in tab as the default option. If you try to push the file as a file stream it will more than likely just load it in a new tab as well.

Cant use that option as it is client request we cant configure each browser. I want to avoid it as it is heavy on server as sending out pdf as a stream take server resources.

<a href="handlePDF.aspx?file=file1.pdf" download target="_blank">File One </a>

I have to create handlePDF.aspx first otherwise it will get page not found error. I have already tried download target="_blank" previously on the link it doesn't work

c# - Open PDF file with Save As option in webform - Stack Over...

c# pdf webforms
Rectangle 27 0

bypass the dialog box and automatically download the file

If using Firefox, you can try the following settings. Make sure to set your /path/to/downloads and Content-Type ( application/download, application/octet-stream, text/csv, etc.)

fp = webdriver.FirefoxProfile()
fp.set_preference("", '/path/to/downloads/')
fp.set_preference("", '/path/to/downloads/')
fp.set_preference("", '/path/to/downloads/')
fp.set_preference("browser.helperApps.neverAsk.openFile", "CONTENT-TYPE")

Then make sure to pass that profile to your instance of the browser:

mydriver = webdriver.Firefox(firefox_profile=fp)

There is a new browser window being opened with these preferences set , am i doing something wrong ?

Yea for some reason, I had two instances of webdriver.Firefox(). It should just be mydriver = webdriver.Firefox(firefox_profile=fp)

javascript - Working with dialog box to download file from a site in p...

javascript python selenium urllib2 mechanize
Rectangle 27 0

I have done something like this to get the file .

protected void btnExportFile_Click(object sender, EventArgs e)
                Thread newThread = new Thread(new ThreadStart(ThreadMethod));

               // try using threads as you will get a Current thread must be set to single thread apartment (STA) mode before OLE Exception .

            catch (Exception ex)



        static void ThreadMethod()
            Stream myStream;
            SaveFileDialog saveFileDialog1 = new SaveFileDialog();
            saveFileDialog1.FilterIndex = 2;
            saveFileDialog1.RestoreDirectory = true;

            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
                if ((myStream = saveFileDialog1.OpenFile()) != null)
                    // Code to write the stream goes here.

c# - Save dialog box to download file, Saving file from ASP.NET server...

c# save save-dialog
Rectangle 27 0

I find AutoIt very useful for these kind of tasks. If you want to integrate it with your C# app, then you can call your AutoIt script via system calls. The difficulty is finding and following the link on the page, that will depend on how the page is laid out.

browser - Automatically select save option in webbrowser file download...

Rectangle 27 0

The action the browser takes depends on a couple of things; the MIME type that the server sends it for the file, but also on how the browser is configured to handle that particular MIME type. You can set the MIME type on the server end with:

response.setContentType( "application/octet-stream" );

That MIME type should generally show a save dialog, but the user could potentially configure their browser to handle it differently.

java ee - downloading file with save as dialog box in to pro...

jsp java-ee spring-mvc file-upload file-io
Rectangle 27 0

Assuming you know the mimeType and filename of your file, you can set the content type and the HTTP header Content-Disposition.

Just write the byte array to the OutputStream:

// The response from your servlet.
    HttpServletResponse resp;
    resp.setHeader("Content-Disposition", "attachment;filename=" + filename);

Thank you for the answer. About the mimeType, can we get it without the file name?

you can use mimeType or the Content-Disposition header alone. But to find out the mimeType of the file is very difficult without the file name (and keep in mind, that the file name is not necessarily accurate, as well). -- Typically, you "guess" the mimeType based on the file name suffix (JPG, WAV, MP3 etc.) and store it alongside with the file data.

No, one doesn't "guess" the MIME type. If you only look at the file name that it's indeed a guessing game. Instead you need to check the magic bytes i.e. the first few bytes of a file. It's not complicated but just tedious. or do just that.

java - How to convert a byte[] into a file with a download dialog box?...

java spring spring-mvc
Rectangle 27 0

The byte array can be sent to the client from a servlet. You can find many discussions on the topic here and elsewhere.

Here are folks discussing efficiency of streaming (with code). Here is a discussion on how to map the servlet to a url (with examples).

The last thing for you to do is just link the user to the servlet's URL when they click the button.

You'll also want to look into what additional info you can provide in the header before streaming the byte array. For example, if you provide a mime type the browser then has a clue what to do with the file; open PDFs in the browser, display images in the browser; open xls files in Excel.

java - How to convert a byte[] into a file with a download dialog box?...

java spring spring-mvc
Rectangle 27 0

The FileReference and FileReferenceList classes do not let you set the default file location for the dialog box that the browse() or download() methods generate. The default location shown in the dialog box is the most recently browsed folder, if that location can be determined, or the desktop.

Note: In Adobe AIR, the File class, which extends the FileReference class, provides more capabilities and has less security restrictions than the FileReference class.

actionscript 3 - Adobe air save text file to application directory? - ...

Rectangle 27 0

string fileName = string.Format(Guid.NewGuid()+".pdf");
htmlToPdf(Server.MapPath(@"~\temp\") + fileName);
Response.AppendHeader("Content-Disposition", "attachment; filename=" + FileName);
Response.ContentType = "application/pdf";

c# - Save As dialog box when downloading PDF file - Stack Overflow

c# internet-explorer itextsharp