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

Similar Messages

  • 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

  • Is there a way I can 'select all' for downloading purchase files via family sharing instead of selecting each file or folder one at a time?

    Is there a way I can 'select all' for downloading purchase files via family sharing instead of selecting each file or folder one at a time?

    or home sharing

  • Problem downloading a file via http

    Hi
    I'm just getting started with WLS (sp5) and am having a problem downloading
    a file via http. The document is stored in the main html docs directory and
    whenever I link to it or try to download it directly (eg:
    http://<host>:<port>/myfile.doc) I get the following error in a message box:
    Your current security settings do not allow this file to be downloaded.
    Can anyone point me in the right direction as to where I grant permissions
    to do this - I've tried using the weblogic.security.URLAclFile and adding
    the directory as a weblogic.io.fileSystem (a desperation move, I know).
    Thanks in advance,
    Peter Villiers

    PLEASE IGNORE THIS POST
    The problem was caused by someone (me though I honestly don't remember doing
    it), setting the content security level to high in my web browser which
    stopped this type of download.
    Peter

  • How to download a file via web service in Windows Phone 8.1?

    My project just got 2 part.
    1.Pivot app
    2.Webclient server (provide data for pivot app the view the data)
    My concert that how do i do a download button to download a file via web services in to isolated storage.
    urgent!

    something like this:
    public async System.Threading.Tasks.Task DownloadFile()
    using (var client = new Windows.Web.Http.HttpClient())
    var stream = await client.GetInputStreamAsync(new System.Uri("http://urltomyfile"));
    var file = await ApplicationData.Current.LocalFolder.CreateFileAsync("myfile.txt", CreationCollisionOption.GenerateUniqueName);
    using (var fileStream = await file.OpenAsync(FileAccessMode.ReadWrite))
    IBuffer buffer = new Windows.Storage.Streams.Buffer(1024);
    while ((buffer = await stream.ReadAsync(buffer, buffer.Capacity, InputStreamOptions.None)).Length > 0)
    await fileStream.WriteAsync(buffer);
    await fileStream.FlushAsync();
    how is your webservices offering the file?
    Microsoft Certified Solutions Developer - Windows Store Apps Using C#

  • Downloading a file in JSP & Servlet

    Hi all
    I want to download a file from a server to the local machine using JSP.
    Kindly send me solution on this if any body has any info on this.
    Also is it possible to download a file from a server to the local machine using servlets.
    Do send me the soluton as soon as possible.
    Rgds,
    Satya

    http://www.jguru.com/faq/view.jsp?EID=10646

  • 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

  • After some running time I cannot download large files via any browser.

    I am running OS X 10.9.2 on a 27inch iMac 2013 model.
    If I keep it running (without sleeping) for some time, perhaps a week, I can no longer download any large files via any browser. It will start and after a very short time go down to 0 B/s, stall there and at the end aboft with an "Unknown network error" or something similar.
    Has anyone seen similar problems?

    Open router set up using http://192.168.1.1  .....you will see username & password .....leave username blank & in password use admin...............
    Click status tab..........check firmware version .......download the latest firmware from http://linksys.com/download ..........
    Udate the firmware ....reset the router for 20-30 seconds ........ later on reconfigure the router ........

  • Error while downloading a file via APEX screen

    While I try to download a file using the below code;
    an HTTP 404 error is coming although the proc is being called and the parameter is correctly being passed.
    Please help.
    create or replace procedure download_myfile1(p_id in number)
    as
    v_mime varchar2(255);
    v_length number;
    v_file_name varchar2(2000);
    Lob_loc BLOB;
    BEGIN
    -- -- Selecting the details from the table whoch contains the extracts
    select EXTRACT_FILE,FILE_NAME,dbms_lob.getlength(EXTRACT_FILE) into lob_loc,v_file_name,v_length from table_name where ID = p_id;
    -- -- set up HTTP header
    -- -- use an NVL around the mime type and
    -- if it is a null set it to application/octect
    -- application/octect may launch a download window from windows
    owa_util.mime_header( 'application/octet', FALSE );
    -- set the size so the browser knows how much to download
    --v_file_name := substr(v_file_name,1,instr(v_file_name,'.')-1);
    htp.p('Content-length: ' || v_length);
    -- the filename will be used by the browser if the users does a save as
    htp.p('Content-Disposition: attachment; filename="'||v_file_name|| '"');
    -- close the headers
    owa_util.http_header_close;
    -- download the BLOB
    wpg_docload.download_file( lob_loc );
    end download_myfile1;
    It shows a POP up window by which u can save or opens the file. But no pop up displayed in this case.
    -Shreya

    Hi,
    Made the same changes but still getting the same error.
    The earlier URL also that I had mentoned would dynamically make this url mentioned by you and then shows the pop up window.
    However when I am right clicking on the download link and then clicking 'Save target as' then this error message is provided:
    Internet Cannot download [schema name].download_myfile2 from [DNS name]
    Internet Explorer was not able to open this Internet Site.The requested site is either unavailable or cannot be found .Please try again.
    Please help..
    Thanks in Advance ...
    Shreya
    Edited by: 935203 on Jul 9, 2012 11:58 PM

  • Unable to download large files via my Mobile Network

    I have unlimited mobile data but I am unable to download large files, like podcasts unless I connect to Wi Fi. My settings are set to use mobile data, is there anything I can do?

    There is a 50meg (recently upgraded from 20) per file download limit over cellular data. No, you can't change that.

  • Downloading linked files via Safari after Leopard upgrade

    Prior to my Leopard upgrade, when I would go to my audio site, I could click on the link and it would play in quicktime no problem, if I wanted to download the file... I would use "option" click.. again no problem. Now after the upgrade, if I click the file, still plays no problem but when I attempt to download the file using "option" click, it downloads the html address as opposed to the actual linked file. And when I use "control" click to emulate a right click, none of those options work either. I get the same result. It downloads the html link only and not the file. This all worked fine prior to the upgrade and my friend who also upgraded is also getting the same exact results. I couldn't find anything in the Safari options so I am at a loss..... Any suggestions?

    I have the same problem... Prior to upgrading to Leopard, I had a folder named "Downloads" located on my desktop that Firefox saved files to. After upgrading to Leopard, I set the new Apple-supplied Downloads folder (located in my home folder) as the default location, but Firefox still refused to download files.
    I manually moved everything from my own Downloads folder (located on the Desktop) to the Apple-supplied folder (in my home folder) and created an alias (for convenience) for this folder on the desktop. Alas, Firefox still refused to download.
    Eventually, I just deleted the alias to the Downloads folder located on my desktop and now Firefox will download just fine. Kinda irritating...

  • Download Excel file using JSP

    Hi All,
    I am working on a JAVA/JSP application. JSP page passes the user inputs to JAVA page (using POST method) which queries to the database and generate an Excel file and returns the link for that file. I am displaying that link in JSP page ("Your file is successfully saved. Click here to download or view your file).
    Now what I want is when the user clicks on the link, open/save dialog will appear which give flexibility to the user to download or view the file in same JSP page. The problem is I don�t want to post again the data or dont want to open a child window. How to set the content type without posting it (I don�t know much about this). Is there any way to do this?
    Any help is highly appreciated. Thanx in advance
    Cheers
    Inderpal

    Hi
    Iam retreiving a file which is in image type in Ms SQl database, but while im retreiving the data from database using Servlet OutputStream the data is showing in binary format with all speciall symbols and text inside .Iamunable to find the solution for that,
    Pleas help me
    my code
              response.setContentType("application/msword");                    
                   OutputStream ros = response.getOutputStream();
              ros.flush();
                   ros.write(bt,0,bt.length);
    Thankz for ur help ,
    my id: [email protected]

  • Problem downloading large files via Safari

    When downloading large video files (for example, from FilesAnywhere.com), my download stars off OK and then slowly gets slower and slower... and slower and then seems to grind to a halt. I'm currently attempting to download a 165MB file which has taken all day so far, and the time remaining just gets longer and longer. It now stands at another 18 hours, but by the morning it will most likley tell me there's a week left.
    Does anybody know what is causing this? I can download via FTP with no problem very fast -it's just via Safari that seems to be the problem. I'm on a home broadband account.
    I've encountered this problem before and I just had to give up on the download.

    Good to see the problem was solved from the suggestion provided. Glad to have helped.
    Aloha from Big Island.

  • To download a file through JSP

    I have a JSP page on which there is a Button, when clicking this button it must open a new browser window with "save file as" dialog.
    How can i do this in JSP. Note that the user cant see or find the diretory in which files are stored.
    I have seen that in ASP it is possible . is it possible in JSP .
    renjith

    Many file types are causing a download by simply linking them: http://..../sample.exe Others may be saved by "save as".

  • Download a file using jsp

    Hi All,
    I have a jsp with which I download the .Excel file from server, I am using i.e 6 my problem is when I click on download link it opens the file in same browser, How I can force it to open in excel not in a browser. It works fine fire fox.
    Please help.
    Thanks

    You need to set the correct response headers, these work fine for me:
    //control cache, these make the difference
    response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
    response.setHeader("Pragma", "Public");
    //these are xls specific
    response.setHeader("Content-Disposition", "attachment; filename=action.xls");
    response.setHeader("Content-Type", "application/vnd.ms-excel");Does this help you? Otherwise let us know which framework you're using so we can provide you with more details.

Maybe you are looking for

  • How to replace Match library with new library

    Been using iTunes as my music manager/player since 2003. Currently have about 5,000 songs which are a mix of selective CD song rips, iTunes purchases and Amazon Mp3 downloads. Lots of missing artwork, incomplete albums, wrong genres, etc. I use iTune

  • How to create a new ASM Diskgroup in Oracle 10g RAC?

    Hi, Our env is Oracle 10g R2 RAC on HP-UX. I want to create a new ASM Diskgroup. Please let me know if the following steps are ok to create a new ASM Diskgroup. 1. Ensure the new Disk is visible in both ASM instances in RAC (v$asm_disk) and the heade

  • 3gs phone showing "No Service"

    I bought a iphone 3gs from a dodgy cell store. it worked fine until i upgraded the software to 6.1.3. after that the phone displays No Service and wont pick up any sim card and i am not able to use the phone at all. i have tried everything that i kno

  • TS4002 missing a plugin for mail

    I recieved a forwarded e mail from my husband, he sent it from his iphone but he has a windows based e mail account. This email contains links in the original but only blank placeholders in my icloud.com account. When I opened it through Mail underne

  • Crystal Dictionnaries

    Hi, We recently convert our crystal reports from 8.5 version to CR XI Release II, professionnal. So, we've find some other things haven't been convert and we want to know how to convert it and if we've to buy a complement to CR XI. Thank you to help