Download file via jsp

dear all,
to download a *.txt-file via jsp i use following code:
java.io.File file = new java.io.File("C:\\FileName.txt");
response.setHeader("Content-Disposition", "attachment;filename=\""+file.getName()+"\";");
response.setContentType("APPLICATION/OCTET-STREAM");
response.setContentLength((int) file.length());
if(file.isFile()){
     java.io.FileInputStream fis = new java.io.FileInputStream(file);
     java.io.BufferedOutputStream bos = new java.io.BufferedOutputStream(response.getOutputStream());
     byte b[] = new byte[(int)file.length()];
     int read = 0;
     while((read = fis.read(b)) != -1){
          bos.write(b,0,read);
     bos.flush();
     fis.close();
     bos.close();
} the problem is:
the file will be displayed in the browser IE6 (inline), but i want to open a save-dialog!
any ideas?!
thanks for help. andy

up to now i tried another browser (mozilla firebird) and several settings about the contenttype like:
- application/x-download
- application/x-msdownload
- application/x-octet-stream
- application/octet-stream
- application/download
... and the file-name like:
*.zip
*.txt
*.exe
but the browser shows the content of the file always inline (even *.zip and *.exe files!!).
anyway, thank you for help.
andy

Similar Messages

  • How to download files in jsp code {through save dialog}

    can you help me to download files in jsp code {through save dialog}
    i use the following code but it saves the jsp page instead of the downloaded file but with the name of the wanted file to be downloaded
    response.setHeader("Pragma", "public");
    response.setHeader("Cache-Control", "no-cache");
    *** download file
    if((trans !=null)&&(trans.equals("download")) )
    response.setContentType ("application/x-download");
    response.setHeader ("Content-Disposition","attachment;filename=\""+fileName+"\"");
    %>
    <script>
    window.location.href=<%=gallerypath+fileName%>';
    </script>
    <%
    trans="";
    //System.out.print("download : "+fileName );
    //***************************************

    Can you try below code, It should work...
    <%
    String myFileName = request.getParameter("fileName");
    response.setContentType("application/octet-stream");
    response.setHeader("Content-Disposition", "attachment; filename=\"" + myFileName + "\"");
    String root = "D:/";
    InputStream in = null;
    ServletOutputStream outs = response.getOutputStream();
    try {
    in = new BufferedInputStream
    (new FileInputStream(root + myFileName));
    int ch;
    while ((ch = in.read()) != -1) {
    outs.print((char) ch);
    finally {
    if (in != null) in.close(); // very important
    outs.flush();
    outs.close();
    in.close();
    %>

  • Download file via Browser window

    Hello,
    I have a question about downloading a file. How can i Download the file via the browser ? I did get it working to download with flex but also get
    "Error: Error #2176" this error with flash 10 which is not good :-/
    Is there a way to download a file via the browser . i.e : with firefox download window , etc.
    I have seen weborb doing it while i was downloading the weborb application, and i wanted to know if anyone has any idea or sample on how to get this done.
    Help is appreciated .
    Thanks.

    You could write a Javascript function in the HTML page that accepts a URL string as its parameter. This function get then open a new window with this url. You could invoke this function it via the ExternalInterface API in Flex. I believe that would invoke the Firefox Download Manager.

  • Download file via terminal

    I want to download a http file via terminal, whats the command?

    curl -O http://path-to-file
    or
    curl -O ftp://path-to-file
    etc.
    FYI, That's the letter Oh, not the number Zero

  • Problem while executing batch file via jsp

    Scenario 1+
    I have a batch file(.bat) in which i have the following code
    mkdir d:\test\test1;
    mkdir d:\test\test2;
    mkdir d:\test\test3;
    mkdir d:\test\test4;
    mkdir d:\test\test5;
    mkdir d:\test\test6;
    mkdir d:\test\test7;
    mkdir d:\test\test8;
    mkdir d:\test\test9;
    mkdir d:\test\test10;when i double click on this or execute via cmd all the 10 directories are created successfully.
    Scenario 2+
    But when i try to execute this through a jsp using the following code,Only first 5 directories are created.Please help me in resolving the issue ASAP.Thanks in advance
    <%@page import="javax.swing.*"%>
    <%@page import="javax.swing.JFileChooser"%>
    <%@page import="java.awt.event.*"%>
    <%@page import="java.awt.*"%>
    <%@ page import="java.io.*"%>
    <%@ page import="java.util.*"%>
    <html>
      <head>
        <meta http-equiv="Content-Type" content="text/html; charset=windows-1252"/>
        <title>untitled2</title>
      </head>
      <body><%
            Runtime.getRuntime().exec("d:\\test.bat");
                    System.out.println("Inside Try Block");
                  %>
        hi</body>
    </html>I am using Jdeveloper.

    carrera wrote:
    Then can u suggest any other way how i can invoke a batch file from html/jsp.I think what some of the previous posters wanted to make clear is that jsps are not the place to go calling batch files. Jsp's are normally the view part and don't actually trigger these type of actions directly. Call a servlet to do non-view things...
    If all you want to do is execute an ant file, look for examples for running ant through java api. f.i. here

  • Urgent!! downloading file in jsp

    hi all
    can anyone plz help me in downloading file from my disk
    actual scenario is like this
    i have uploaded file path in database, and whole file in to my disk....
    i have given links to file name and when one clicks the link the file of that link should be downloaded / opened from the path specified in the database
    its really too urgent
    plz help me out

    The replies on this post : http://forum.java.sun.com/thread.jspa?threadID=5170452&messageID=9655276 should give you some idea

  • Downloading file via HTTP

    Hi,
    is it possible or exist some adapter or service, which can
    process(or download) file placed on HTTP server?
    Thanks
    Martin

    Chtira,
    I've done it in JDeveloper with HttpServlet class and not in BPEL. I've overridden the doGet and doPost methods.
    doGet looks something like this:
      public void doGet(HttpServletRequest request,
                        HttpServletResponse response)
        throws ServletException, IOException
        response.setContentType(CONTENT_TYPE);
        PrintWriter out = response.getWriter();
        out.println("<html>");
        out.println("<head><title>Communication</title></head>");
        out.println("<body>");
        out.println("<p>GET method is not supported. Please use POST method for XML messages.</p>");
        out.println("</body></html>");
        out.close();
      }doPost method is a bit more complicated. Basically I'll call my BPEL processes with the XML messages I receive but I'm still struggling with XML validation against a schema in this servlet class.
    When you have the class you have to put something like
      <servlet>
        <servlet-name>HttpServletPost</servlet-name>
        <servlet-class><your package>.HttpServletClass</servlet-class>
        <load-on-startup>1</load-on-startup>
      </servlet>
      <servlet-mapping>
         <servlet-name>HttpServletPost</servlet-name>
         <url-pattern>/Communication/*</url-pattern>
      </servlet-mapping> in your web.xml file.
    Hope this helps you somehow.
    BB

  • Cannot download files via Bluetooth since upgrading to Yosemite

    I cannot download files, E.G. photos and spreadsheets, from my Windows phone to my MacBook Pro Retina since upgrading to OS 10.10 Yosemite.
    I can send files from the MacBook Pro to the Windows phone.
    Tried resetting PRAM, no luck
    Tried unpairing and repairing all devices, no luck
    Tried dumping "bluetooth.plist", no luck
    Tried cold start & Resart after each, no luck
    Devices are paired. Bluetooth Sharing is on.
    Help!

    PROBLEM SOLVED:
    Go to "System Preferences" - "Sharing" - "Bluetooth Sharing" - "Folder for selected items:", and select a folder."
    No folder is selected.
    Prior to the upgrade the Folder had been set to "Downloads", so I reset it to "Downloads" and it now works.
    Praise the Lord!!

  • Downloading a file via JSP

    I am trying to write some code which will generate a file and then download the file
    from my Webserver. When I download the file I get "Error 500: OutputStream already obtained"
    appended to the file. I can't work out why this is so.
    Here is the code I have used to download the file.
    I have also included the file before and after transmission.
    Any help would be appreciated.
    <%@page import="java.net.*,javax.servlet.http.*,javax.servlet.*,java.io.*" %>
    <%
    ServletOutputStream out1 = response.getOutputStream();
    String fileName = (String)request.getParameter("filename");
    // MIME type for pdf doc
    response.setContentType("application/x-download");
    response.setHeader("Content-Disposition","attachment;filename="+fileName+";");
    File f = new File("\\"+fileName);
    FileInputStream stream = new FileInputStream(f);
    BufferedInputStream bis = new BufferedInputStream(stream);
    BufferedOutputStream bos = new BufferedOutputStream(out1);
    byte[] buff = new byte[2048];
    int bytesRead;
    // Simple read/write loop.
    try {
    while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
    bos.write(buff, 0, bytesRead);
    } catch (Exception e) {
    if (bos != null) bos.close();
    e.printStackTrace();     
    finally {
    if (bis != null) bis.close();
    if (bos != null) bos.close();     
    if (stream != null) stream.close();     
    %>
    This is the file on the WebServer
    The Quick Brown Fox Jumps Over The Lazy Dog
    The Quick Brown Fox Jumps Over The Lazy Dog
    The Quick Brown Fox Jumps Over The Lazy Dog
    This is the file after it has been transferred
    The Quick Brown Fox Jumps Over The Lazy Dog
    The Quick Brown Fox Jumps Over The Lazy Dog
    The Quick Brown Fox Jumps Over The Lazy DogError 500: OutputStream already obtained
    Thanks
    Adrian Campbell
    Honda Australia

    The JSP automatically gets an outputstream/writer, and starts writing to the output. In fact thats where the implicit variable "out" comes from.
    Couple of things to be aware of:
    Every carriage return outside of a <% %> tag in a JSP gets converted directly into the html as out.println("\r\n");
    That means the generated servlet has started writing even before you get the outputstream - which is what raises the exception.
    There are two ways to stop this
    1 - write it in a servlet - its purely code, with no HTML so servlet is better suited.
    2 - have no carriage returns outside of JSP tags <% %>. You currently have one - one the very first line. Try it like this:
    <%@page import="java.net.*,javax.servlet.http.*,javax.servlet.*,java.io.*" %><% 
    ServletOutputStream out1 = response.getOutputStream();
    %>  // and no carriage return at the end eitherThat should do it.
    As an aside, if you are going to be generating a text file, then you can use the implicit writer "out" as opposed to the OutputStream.
    Cheers,
    evnafets

  • Securely download files in JSP

    Hello,
              I need to know how to do the following:
              User logs in, password is compared with database, then user can see a
              list of files in "his" directory (which only he can have access to) and
              download them. For every user there is a separate directory with
              different files.
              Login and all the rest ist done with JSP and working, my problem is I
              just don'T have any idea how to solve the problem with the
              directories/files and downloading them. I would really appreciate any
              help like code samples, links, .. whatever
              Thanks a lot in advance
              Kasper M. Nowak
              

    Can you try below code, It should work...
    <%
    String myFileName = request.getParameter("fileName");
    response.setContentType("application/octet-stream");
    response.setHeader("Content-Disposition", "attachment; filename=\"" + myFileName + "\"");
    String root = "D:/";
    InputStream in = null;
    ServletOutputStream outs = response.getOutputStream();
    try {
    in = new BufferedInputStream
    (new FileInputStream(root + myFileName));
    int ch;
    while ((ch = in.read()) != -1) {
    outs.print((char) ch);
    finally {
    if (in != null) in.close(); // very important
    outs.flush();
    outs.close();
    in.close();
    %>

  • How to download file in jsp

    Hi guys,
    I am a new member to this java community. I meet some problems in doing my project, hope you experts can help me.
    I want to add a download button in my jsp code. When users click the button, a file will be downloaded to his local computer. The files are ASCII files with .asc as extension. My server is Apache 1.3.19 with tomcat 3.2.1 . What kind of code should I add to my jsp?
    Anyone's quick response is greatly appreciated.

    Thanks for your reply.
    I have tried to use the hyper link in html. But since it's ASCII file with .asc extension, every time the link is clicked, the file is opened directly instead of offering save option. So maybe some special code is needed.
    Many software web site provides download page. When user clicks the download button, the file will be transfered to user's computer. Does anyone knows how to do it?
    Thanks.

  • All downloaded files via pacman -Syu are corrupted

    I have a fresh install of AL and wanted to do a 'pacman -Syu' before going too far. Well it started fine and was downloading the files (about 20 in the list) and so I left it to finish while I slept last night.
    This morning I wake up and check it and it shows all files that it tried to upgrade/install are corrupted. I'm using the 'Current & Extras' repositories in pacman.conf.
    Is there something that I'm missing or doing wrong or a way to fix this without needing to re-install AL from scratch again?
    rberry88 :?:

    This is somewhat interesting unless I'm misinterpreting it wrong. I go to /var/cache/pacman/pkg and it listed the last 3 items/packages that I installed, I then did df -h and then did 'pacman -Sc' to clear these out and did df -h again:
    [root@tux pkg]# ls
    evolution-1.4.5-4.pkg.tar.gz gnet1-1.1.9-1.pkg.tar.gz pan-0.14.2-1.pkg.tar.gz
    [root@tux pkg]# df -h
    Filesystem Size Used Avail Use% Mounted on
    /dev/ide/host0/bus0/target1/lun0/part8
    22G 1.5G 21G 7% /
    none 251M 0 251M 0% /dev/shm
    tmpfs 2.0G 12K 2.0G 1% /tmp
    [root@tux pkg]# pacman -Sc
    removing packages from cache... done.
    [root@tux pkg]# df -h
    Filesystem Size Used Avail Use% Mounted on
    /dev/ide/host0/bus0/target1/lun0/part8
    22G 1.4G 21G 7% /
    none 251M 0 251M 0% /dev/shm
    tmpfs 2.0G 12K 2.0G 1% /tmp
    [root@tux pkg]#
    So, my opinion would be that it wasn't the disc space that was an issue but most likely a corrupted download or other problem that went away when I cleared the cache and installed the new pacman version.
    rberry88

  • Download File Via JavaScript Calls From Website

    Hello,
    I am currently trying to create a program in c# that will download the file "PracticeProfiles.xls" from this website:
    http://fingertips.phe.org.uk/profile/general-practice/data
    I need to somehow on navigation to this site pass the javascript calls "showExport();exportData();", which will start the download.
    Any help would be greatly appreciated.
    Many Thanks

    The link has a method which apparently works, however I had to modify a few things to make it compile:
    public void DownloadIEFile(Browser browser)
    HwndSource source;
    source = HwndSource.FromHwnd(WatiN.Core.Native.Windows.NativeMethods.GetWindow(browser.hWnd, 5));
    Window windowMain = source.RootVisual as Window;
    System.Windows.Automation.TreeWalker trw = new System.Windows.Automation.TreeWalker(System.Windows.Automation.Condition.TrueCondition);
    System.Windows.Automation.AutomationElement mainWindow = trw.GetParent(System.Windows.Automation.AutomationElement.FromHandle(browser.hWnd));
    source = HwndSource.FromHwnd(WatiN.Core.Native.Windows.NativeMethods.GetWindow(new WindowInteropHelper(windowMain).Handle, 5));
    Window windowDialog = source.RootVisual as Window;
    // if doesn't work try to increase sleep interval or write your own waitUntill method
    Thread.Sleep(1000);
    windowDialog.Activate();
    System.Windows.Automation.AutomationElementCollection amc = System.Windows.Automation.AutomationElement.FromHandle(new WindowInteropHelper(windowDialog).Handle).FindAll(System.Windows.Automation.TreeScope.Children, System.Windows.Automation.Condition.TrueCondition);
    foreach (System.Windows.Automation.AutomationElement element in amc)
    // You can use "Save ", "Open", ''Cancel', or "Close" to find necessary button Or write your own enum
    if (element.Current.Name.Equals("Save"))
    // if doesn't work try to increase sleep interval or write your own waitUntil method
    // WaitUntilButtonExsist(element,100);
    Thread.Sleep(1000);
    System.Windows.Automation.AutomationPattern[] pats = element.GetSupportedPatterns();
    // replace this foreach if you need 'Save as' with code bellow
    foreach (System.Windows.Automation.AutomationPattern pat in pats)
    // '10000' button click event id
    if (pat.Id == 10000)
    System.Windows.Automation.InvokePattern click = (System.Windows.Automation.InvokePattern)element.GetCurrentPattern(pat);
    click.Invoke();
    However I am getting null when I try to get the hwnd source, can't see why?
    Any Suggestions?
    Many Thanks

  • Download file via www

    Hi, I need help, I want download large file from internet and don't know, if downloading exit and file still is not download, how then download only non-downloading part of file. Can you help me?

    Right click
    Save Target as
    If the file does not download, it is likely a corrupt file and you should contact the webmaster.

  • Cannot download files via FTP

    I have internet connection on a MAC machine. I am trying to download a driver from HP's website using safari internet browser. I get the below message every time:
    Safari can't open the page "FTP://FTP.hp.com....". The error is: "Unknown error" (NSURLErrorDomain: -1).
    Actually am new to Safari... any help?
    Thank you,

    If this is still giving you the same result, and I am able to download from both links, this suggests something in your connection or with your installation of Safari (I used Safari and that was OK). Have you tried with another browser?
    If that is successful, then the Safari settings may need looking at. If not, the network settings may be awry.
    What DNS settings are you using? (See System Preferences> Network> Advanced. If these are automatically entered by OS X (usually the router), try Open DNS: 203.144.207.29 and 208.67.222.222 (these are what I am using).
    Do you have another account you could try in? That might narrow it down to network or the user account version of Safari. You might also try to set up another Location (network settings), entering the details manually rather than duplicating.
    As for FTP, Macs will also have no problems with FTP, so I am sure it is not platform specific, especially as I did download the driver from that URL you gave. 2MBPS should be ample.
    Now this is odd. While I was able to open that page yesterday, clicking on the link in the message gave me the same result as you. However, if I go to this page -- http://h20000.www2.hp.com/bizsupport/TechSupport/SoftwareIndex.jsp?lang=en&cc=us &prodNameId=445195&prodTypeId=18972&prodSeriesId=445194&swLang=8&taskId=135&swEn vOID=219 -- and click on the Download link lower down the page, that does work properly.
    Curioser and curioser.

Maybe you are looking for

  • Cost component view German instead of English

    When I display product cost estimate with quantity structure. Under the tab costs all the cost component view description show up in German. In our development and test client they show up fine in English. I don't know if this problem has any thing t

  • ALV GRID - Get setting of the variants

    Dear All, I have a program which provides a list with ALV - the user can give his ALV variant on the selection-screen. I have to know the setting of the variant chosen - Field - Sort - subtotal - This program could be ran in background, that why I ha

  • Using Hint option to optimise queries for remote tables

    1. How do i provide a hint to access indexes for remote tables in my query? 2. The explain plan in the 'TOAD' does not expand for remote tables, ie there is no way i can find out whether my query is using the remote table index or not. Any help on th

  • Fade to Slideshow ?

    Wen I use Tiger's built in slideshow feature, I get an odd transition. My desktop fades to black as expected, but then reappears as if interrupted, and then starts the show. Any ideas why? Any insights what I could do to fix this?

  • BBW and Speaker issues

    I'm recently bought new BB Z10 and I'm facing two issues: 1- BBW not opened. 2- Speaker not working. I searched in the internet and tried all below solution without any sucsse: - Remove battery and restart the phone, - Open music and remove phone cov