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();
%>

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 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

  • 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

  • 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.

  • Path and file name problem when I want to download files from html

    Hi all,
    I want to write a small program to allow users download files from jsp file
    but the following files don't work .
    <%@ page language="java" import="java.net.*,java.io.*"%>
    <%@ page import ="java.util.*"%>
    <%
    try
    String SContent = request.getParameter("click");
    String SDocName = "temp.doc"; //  out put file File Name
    ServletOutputStream stream= response.getOutputStream(); // Getting ServletOutputStream
    response.setContentType("application/msword"); // Setting content type
    response.setHeader("Content-disposition","attachment;filename=\"" +SDocName+"\""); // To pop dialog box
    BufferedInputStream in = new BufferedInputStream(new FileInputStream(SContent));
    int c;
    while ((c = in.read()) != -1){
               stream.write(c);
    in.close();
    stream.flush();
    catch(final IOException e)
    System.out.println ( "IOException." );
    catch(Exception e1)
    System.out.println ( "Exception." );
    %>I am so confuse, what is the path and file name I sould give ? for example my click should equal to http://******/Test/display.jsp?click=00-1

    Hi all,
    I got error at
    java.lang.IllegalStateException: getOutputStream() has already been called for this response
         org.apache.coyote.tomcat5.CoyoteResponse.getWriter(CoyoteResponse.java:599)
    if I want ot download file from html file.
    String SContent = request.getParameter("click");
    if I hard code like follow it work fine.
    String SContent ="C:/Project Coding.doc";
    what mistake I make.
    Thank you!

  • Creating a file download link on jsp

    I have the following on my jsp. The code worked fine until I tried to use it in a new html design page.
    <code>
    //page name is index.jsp
    try //DISPLAY THE CONTENTS OF THE DATA DIRECTORY
    File dirname = new File(PATH); // create an instance of the File class
    if (dirname.exists()&&dirname.isDirectory())//check to see if File class dirname exists and is valid
    String [] allfiles = dirname.list();//create an array of files in the dirname File class
              for (int i=0; i< allfiles.length; i+=2)//loop through allfiles[] and print out file links
    out.println("<br><table border='1' cellspacing='1' width='99%'>");
                   out.println("<tr><td width='50%' class='pageFont'><input type='checkbox' name='cb' value='"+allfiles[i]+"'>"+allfiles[i]+"      ");
    %>
    <a class="a" href="index.jsp?downfile=C:\\data\\<%=allfiles[i+1]%>">DOWNLOAD</a></td>
    <% if(i+1 < allfiles.length)//PRINTS OUT THE SECOND TD SO THAT WE HAVE 2 COLUMNS OF LINKS
    out.println("<td width='50%' class='pageFont'><input type='checkbox' name='cb' value='"+allfiles[i+1]+"'>"+allfiles[i+1]+"      ");
    %>
    <a class="a" href="index.jsp?downfile=C:\\data\\<%=allfiles[i+1]%>">DOWNLOAD</a></td></tr>
    <%
    out.println("</form></font></table>");
    catch (IOException excep)
         out.println("An IO exception has occured.");
    </code>
    Then when clicked this code is run:
    <code>
    try{
    //CHECK TO SEE IF THE FILE HAS BEEN CLICKED TO DOWNLOAD SINGLE FILE
    if (request.getParameter("downfile") != null)
    String filePath = request.getParameter("downfile");
    File f = new File(filePath);//CREATE AN INSTANCE OF THE FILE CLASS AND POINT IT TO THE LOCATION OF THE DIRECTORY CONTAINING THE FILES
    if (f.exists() && f.canRead())
    response.setContentType ("application/octet-stream");
    response.setHeader ("Content-Disposition", "attachment;filename=\""+f.getName()+"\"");
    response.setContentLength((int) f.length());
    BufferedInputStream fileInputStream = new BufferedInputStream(new FileInputStream(f));
    int i;
    out.clearBuffer();
    while ((i = fileInputStream.read()) != -1) out.write(i);
    fileInputStream.close();
    out.flush();
    </code>
    When I click on this link I get the download dialog box. If I open it I get the following open up in notepad(the files I am trying to give download links are .txt files)
    Below is what is displayed in notepad ALL on 1 line:
    <html>
    <head>
    <LINK rel="stylesheet" ty
    That is displayed in all of the links that I click on. It is the first few lines of html code for index.jsp.
    I know this code is probably not a good way of doing what I need but I got it to work fine until the change.
    I am sure there is an easier way to code the download link without resubmitting the page.
    Thanks in advance!!

    Well all was fine with this jsp until I moved it to ApacheJServ. Now the problem has resurfaced(although it is a little different now)
    I had moved the following code to the top of my page:
    //CHECK TO SEE IF EITHER DOWNFILE OR ZIPFILE VARIABLE EXIST, AND IF THEY DO SET CONTENT TYPE BEFORE SENDING ANY HTML CODE TO THE BROWSER
    try{
    //CHECK TO SEE IF THE FILE HAS BEEN CLICKED TO DOWNLOAD SINGLE FILE
        if (request.getParameter("downfile") != null)
                String filePath = request.getParameter("downfile");
                File f = new File(filePath);//CREATE AN INSTANCE OF THE FILE CLASS AND POINT IT TO THE LOCATION OF THE DIRECTORY CONTAINING THE FILES
                    if (f.exists() && f.canRead())
                        response.setContentType ("application/octet-stream");
                        response.setHeader ("Content-Disposition", "attachment;filename=\""+f.getName()+"\"");
                        response.setContentLength((int) f.length());
                        BufferedInputStream fileInputStream = new BufferedInputStream(new FileInputStream(f));
                        int i;
                        out.clearBuffer();
                        while ((i = fileInputStream.read()) != -1) out.write(i);
                            fileInputStream.close();
                            out.flush();
                            response.flushBuffer();
    catch (Exception e){}
    //This is where the java code ends and the javascript/html code begins.Then further into the page I create the file download links like so:
                            <a class="a" href="main.jsp?downfile=C:\\data\\<%=allfiles[i+1]%>">DOWNLOAD</a>I know this isnt a secure way of doing this but I am on a intranet.
    The problem I am having now is that when I click on one of the links and download the file and then open it, I get the contents of the file plus concatenated to the end of it is the first few HTML lines of the actual jsp that I downloaded the file from. Before I was just getting the first few lines of html from the jsp, not the actual contents of the downloaded file.
    This is an example of what I am getting:
    This is the contents of the file that I downloaded.//This is where the file contents ends.
    <html>
    <head>
    <LINK rel="stylesheet" type="text/css" href="default.css">
    <script language="JavaScript1.2">
    //function that allows user to select all checkboxes
    function doIt(v)
    for(var i=0;i<document.form1.cb.length;i++)
       document.form1.cb.checked=eval(v);
    function swap(imageName,image)
    imageName.src = "templateImages/"+image;
    function imageOver(imageSrc, imageName)
         changeImage = new Image();
         changeImage.src = imageSrc;
         document.images[imageName].src = changeImage.src;
    var hide = true;
    function hideShow( ) /
    Any morre ideas?
    TIA!
    BTW, I went to ApacheJServ because they wont let me use tomcat :(

  • How to download a text file using jsp i

    I want to provide download facility in jsp page.
    if i have exe download is working . If I have a text / html file it is just displaying I want to make it download How to do it?
    regards
    subrahmanayma

    If you want to get an "Save as" dialogue, then you need to set the content-disposition in the header to "attachment". The default value is "inline".
    Best solution is to create kind of a FileServlet and let it stream the right file as a download to the client. You may find the downloadFile() snippets at the bottom of this article useful: http://balusc.xs4all.nl/srv/dev-jep-pdf.html Put it in a FileServlet and call it using for example .

  • When I try to open the downloaded file, a security warning restricts me from opening the file.

    I have the new Motorola Bravo which is on the Android 2.1 system. When I try to open the downloaded file, a warning appears saying "This application comes from an unknown source, and for your security only applications from trusted sources can be installed". Is the download corrupt? I would think not, but I am very confused.

    Unfortunately, AT&T disables the ability for its Android phones to install applications that aren't distributed through the Android Market.
    If this phone is not AT&T-branded, then you might be able to enable "Non-Market sources" in the "Applications" section of the Settings app.
    If it is, then you might be able to use the Android developer tool "adb" to install Firefox on your phone (search the web for instructions), or you can wait for our next beta release which should be available through the Market later this month.

  • Converting an html file with jsp contents to a text file for download

    Hi guys,
    I'm currently having troubles with downloading a .jsp file to a doc file.
    The thing is i am able to download the desired file and make it as a .doc but when i open it with ms word 2007 i can only see the content of the html. The dynamic content generated from the database and reflected on the .jsp page that i suppose to download and convert to .doc file doesn't show.. I hope someone could help me... My servlet code is this:
    public class FileDownload extends HttpServlet
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    try
    String originalFileName="localhost:8080//Appsdev//reportresults1.jsp";
    File f=new File(originalFileName);
    System.out.println("THE 1st f:"+f);
              response.setContentType("application/octet-stream");
    response.setHeader("Content-Disposition", "attachment; filename=tryreport.doc;");
    response.setHeader("Cache-Control", "max-age=0");
    byte[] buf = new byte[1024];
    FileInputStream inStream = new FileInputStream(f);
    OutputStream outStream = response.getOutputStream();
    int sizeRead = 0;
    int size = 0;
    while ((sizeRead = inStream.read(buf, 0, buf.length)) != -1)
    outStream.write(buf, 0, sizeRead);
    size += sizeRead;
    inStream.close();
    outStream.close();
    catch(Exception e)
    e.printStackTrace();
    }

    Hi BalusC,
    sorry for the double post i'm newly registered and it's my first post before i was just reading other's threads.
    well last night while i was reading and researching for a solution a came across this.
    <%@ page language="java" contentType="application/msword"%> naturally for my other jsp pages, the contentType is text/html so when the page loads it display in the browser. But with application/msword when i direct the page to the jsp page that i want to download and set the contentType with that...it prompts a window like when you're downloading the one with the <open with and save as>. It works fine to, i was able to see the report that i have to download and it is formatted very much like what i am seeing on the browser. My only concern now is the file i am able to download is a .jsp file how could i change that to a .doc file and be able to see the same content like the one with the .jsp file that i have right now.... any help or examples would be greatly appreciated. I didn't use the servlet anymore because even though i am able to download there is no content the html parts only but iam able to change the extension for the file...thanks again! ^ ^

  • I can't download files or videos, I get the response "The object is blocked" As far as I know I have removed or disabled all security programs

    I am unable to play streaming video, and can't download anything. I have removed or disabled all of my security programs.
    == This happened ==
    Every time Firefox opened
    == About 2 weeks ago, downloaded most recent Windows service pack

    HI Phillip,
    On the other I am wholly unable to download the file from either Safari or Firefox
    Let's try one browser at a time. Open a Finder window. Select your Home folder in the Sidebar on the left. Then open the Library folder then the Safari folder. Move the Downloads.plist file from the Safari folder to the Trash. Relaunch Safari.
    If that didn't help, from your Safari menu bar click Safari / Reset Safari. Select the top 7 buttons, click Reset.
    Now launch Firefox. From the Firefox menu bar click Firefox / Preferences then select the
    Advanced tab then the Network tab. Click: Clear Now.
    Relaunch Firefox.
    If nothing above has helped either browser, login to your Mac to another user account. Try Safari there. If you can't download files from Safari there, then it's a system wide problem. Boot from your install disc. Run Disk Utility to verify and if necessary, repair any errors on the startup disk.
    Help here for Disk Utility: The Repair functions of Disk Utility: what's it all about?
    Carolyn

  • Why I have 3 empty ligns in the file downloaded with a JSP

    Hello,
    When a user select some data (extracted from an Oracle database), he could save the data in a flat file. To do this functionnality, I use a JSP which creates a file with the result of the query, and I download to the browser the file by using :
    response.setHeader("Cache-Control","no-store");
    response.setDateHeader("Expires",1000);
    response.setContentType("application/x_msdownload");
    response.setHeader("Content-Disposition","attachement;filename=" + outputFile);
    I could save or open the file.
    BUT I have 3 empty ligns at the begining of the downloaded file.
    Do you know why?
    Next, is it my code of the JSP used to create the file on the server, download it to the browser and delete it:
    <%
    currentReport.load(currentConnection, reportNm, whereCond, inputFile);
    response.setHeader("Cache-Control","no-store");
    response.setDateHeader("Expires",1000);
    response.setContentType("application/x_msdownload");
    response.setHeader("Content-Disposition","attachement;filename=" + outputFile);
    File fin = new File( inputFile);
    if (! (fin.canRead() || fin.isFile()))
    SecurityException se = new SecurityException( inputFile);
    throw se;
    BufferedReader br = new BufferedReader(new FileReader(fin));
    while ((currentLine = br.readLine()) != null)
    out.println( currentLine);
    br.close();
    currentReport.deleteReport();
    response.flushBuffer();
    %>

    I wouldn't use JSP for this, I'd use servlets...
    But the reason is cuz you have 3 lines before the data is written, say like this:
    <@page import="..." >[newline]
    <@page import="..." >[newline]
    <%
    response.setHeader...
    %>[newline]
    <%
    code to get the file...
    %>

  • JSP, downloading files and show html page

    I like to download files and show a html page on JSP.
    With the source following, downloading works well.
    But, it is just remained on the previous page, not showing the next html page.
    Someone tell me why is it?
    <%@ page import="java.io.*, java.net.URL"%><%
    String file_name = request.getParameter("file_name");
    File fileDir = new File(config.getServletContext().getRealPath("upload/"));
    File theFile = new File(fileDir, file_name);
    FileInputStream fin = new FileInputStream(theFile);
    response.setHeader("Content-Disposition","attachment; filename=\"" + theFile.getName()+"\"");
    response.setContentLength((int) theFile.length());
    BufferedInputStream bf = new BufferedInputStream(new FileInputStream(theFile), 8096);
    int i;
    while ((i=bf.read()) != -1)
    out.write(i);
    bf.close();
    out.close();
    %>
    <html>
    <head>
    <title>file download</title>
    </head>
    <body>
    <p align="center"> </p>
    <p align="center"><b><font face="Tahoma" color="#000000" size="2">You have
    successfully downloaded your file(<%=file_name%>)!</font></b></p>
    </body>
    </html>

    You's already close the JSP output stream befor you try and write your html confirmation, and I don't think browsers can provide the kind of functionality you're trying to demonstrate here. A browser will download the file and open it directly itself or using another application based on user input (e.g. save as, open file, etc.). Once the file is opened or downloaded, it's done!
    I think your best bet is to show a dialogue that the user's download should begin, then set the pages href w/ JS to the location of the file, same way other sites that allow you to download files do it. Go take a look at download.com or something like that.
    Hope that helps.

  • Downloading file

    Hi all,
    i have a jsp page with download button on it...when i click on download button, it starts downloading file.
    now the problem is if the IE setting has high security....
    it will prompt to download file....on clicking allow downloading file...the whole page gets refreshed and the data in my jsp page to download is loss.....
    how to restore that file for downloading...???
    Thanks

    i am using ajax for this...
    i have index.jsp , filecreator.jsp and pdf download.jsp pages
    pdfdownload.jsp
    <%@page     import="java.io.*"%><%
    String path = request.getParameter("sPath");
    String Filename = request.getParameter("sTitle");
    //System.out.println("Path = " + path);
    //System.out.println("File = " + Filename);
    String PDFfile = Filename;
    response.setHeader("Cache-Control", "no-cache");
    response.setDateHeader("Expires", 0);
    response.setHeader("Pragma", "No-cache");
    try {
    response.setContentType("application/pdf");
    String disHeader = "Attachment;Filename="+PDFfile;
    response.setHeader("Content-Disposition", disHeader);
    File file = new File(path);
    FileInputStream fileInputStream = new FileInputStream(file);
    int i;
    while ((i=fileInputStream.read())!=-1)
    response.getOutputStream().write(i);
    response.getOutputStream().flush();
    response.getOutputStream().close();
    fileInputStream.close();
    catch (Exception e) {
    System.out.println(e.getMessage());
    %>i have a form in index.jsp as
    <form id="frmd" name="frmd" method="post" action="/vpppoint-calculator/cust/resource/jsp/pdfdownload.jsp">
            <input name="sTitle" type="hidden" value="">
            <input name="sPath" type="hidden" value="">
            </form>please help....thanks

  • HTML tag to upload and Download files

    hello all
    IS there any HtTML tag to upload and download files ???
    rgds
    ASHWIN

    Yea, for downloading you can use a normal link. For uploading, you need an html form like
    <form name="form1" enctype="multipart/form-data" method="post" action="doSomething.jsp">
      <input type="file" name="file">
    </form>To be honest I know nothing about jsp and servlets yet, but I would guess that it works just the same as with php, with which I am alot more familiar. Basicly, the form tag with the input type="file" tag tells the form to submit your file to the webserver.
    Then, whatever script you call with action="anythingYouWantHere" will handle the file the user submitted. There must be very similar functions to handle them in java than there is in php.
    Things to look for with file upload that often are buggy is the permissions / security settings you have on your webserver. Sometimes you need to make a special folder with extra permissions to allow you upload to work.
    Thats about all I know on this matter, good luck :)

Maybe you are looking for

  • Different page sizes in one pdf file will not scale to print correctly

    Hello all,      I have a pdf document that contains three different page sizes; 8.5"x11", 11"x17" and 34"x22".  These pdf files are custom manuals and we print many of these over the course of a month.      In the older versions of Adobe Acrobat when

  • Objects in Fireworks files lose their x,y coordinates

    I am currently using CS4 10.0.3.011 I can create a Firewoks graphic and save it just fine. When I re-open the file to edit it, sometimes the x,y positions of the various objects are scrambled and the pieces end up all over the page. This causes me to

  • Syncronization address book

    I regularly sync my iphone with my powerbook g4 (osx 10.4.11) and I choose always to sync the address book too. However now I cannot get the new conctacts fron my addressbook neither the other way round. So if I add a contact on my iphone I cannot ha

  • UseOneAsMany Function Not Working

    Hi Experts, I have tried the example from the below blog: **************** - Implementation of Node functions I have changed the context level as mentioned in the blog. I have changed the Plant Context Level to Mt_Sender for both MatNo and MatDesc wh

  • Photo Library view with all pics

    I have pics in separate folders synced to the iphone. Some for general viewing others for my viewing only. However, the photo library displays all of the pics. Any way to remove the photo library folder / view?