Problem in downloading file using servlet

Hello,
I wnat to send a file throung servlet to my desktop program. when i call this servlet through internet explore it is working fine but when i call this in my desktop program then desktop program get nothing. my desktop program does not get anything. please help me. here is my both code servlet and desktop program.
public void doGet(HttpServletRequest request, HttpServletResponse response)
               throws ServletException, IOException {
          response.setContentType("text/html");
     //     PrintWriter out = response.getWriter();
          File filename = new File("");
//          Set the headers.
          response.setContentType("application/x-download");
          response.setHeader("Content-Disposition", "attachment; filename=" + filename);
//          Send the file.
          OutputStream out = res.getOutputStream( );
          returnFile(filename, out); // Shown earlier in the chapter
          String filePath = getServletContext().getRealPath("/");
          response.setContentType("application/x-download");
          response.setHeader("Content-Disposition", "attachment; filename="+"amit.doc");
     //     File tosave = new File(getServletContext().getRealPath("), cfile.getName());" +
          try{
          File uFile= new File(filePath);
          int fSize=(int)uFile.length();
          FileInputStream fis = new FileInputStream(uFile);
          PrintWriter pw = response.getWriter();
          int c=-1;
//          Loop to read and write bytes.
//          pw.print("Test");
          while ((c = fis.read()) != -1){
          pw.print((char)c);
//          Close output and input resources.
          fis.close();
          pw.flush();
          pw=null;
          }catch(Exception e){
public class AdDesktopClient {
     * @param args
     public static void main(String[] args) {
          try{ 
          URL url = new URL("http://localhost:8080/WebRoot1/servlet/Download");
          //URLEncoder.encode(xmlString);
          URLConnection connection = url.openConnection();
          HttpURLConnection con = (HttpURLConnection)connection;
          con.setDoInput(true);
          con.setDoOutput(true);
          con.setUseCaches(true);
          con.setRequestMethod("GET");
          // PrintWriter out = new PrintWriter(con.getOutputStream());
          BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
          String inputLine;
          int len = con.getContentLength();
          InputStream inn = con.getInputStream();
          byte[] buf = new byte[128];
          int c =0;
          System.out.print("len :"+len);
          System.out.print(inn.read());
          while( (c = inn.read())!= -1){
               System.out.print(c);
/*          while ((inputLine = in.readLine()) != null)
          System.out.println(inputLine);
          in.close();
          }catch(Exception e){
               e.printStackTrace();
Plaease help me to solve this problem. i want to send a file throuhg a servlet to my desktop program.
Thanks in advance
Ravi

Give this a try:
File strFile = new File(strFileName);
long length = strFile.length();
response.setContentType("application/octet-stream");
response.setContentLength((int)length);
response.setHeader("Content-Disposition", ("attachment; filename=" + strFileName));
OutputStream out = response.getOutputStream();
BufferedInputStream in = new BufferedInputStream(new FileInputStream(strFile));
int i = -1;
while((i = in.read()) != -1) out.write(i);
in.close();
Kris

Similar Messages

  • Download a file using servlet

    Hi,
    i need to download a file using servlet (jsp frontend) and if the download is successful, then a success message shud be displayed on the jsp.
    i have tried it using MultipartResonse object and have been able to download the file. The problem is displaying the message on a jsp after download. After download if i use RequestDispatcher object to forward control to another jsp, it doesnt happen.
    Can anyone help me with this?

    Hi,
    You can check :-
    http://www.servletsuite.com/servlets/download.htm
    Best of luck.
    R S

  • How to parse the xml file using servlet

    My scenario is like this:
    <b>FILE-->XI-->J2EE Application</b>
    XI sends the xml file to j2ee application. My servlet receives the file in HTTPRequest string. 
    How to parse that file using servlets.I should get the xml file as it is and should be displayed in the browser.
    Can anyone please help me with code, its urgent.
    Please help me!

    Download this java code
    http://java.sun.com/webservices/jaxp/dist/1.1/docs/tutorial/sax/work/Echo02.java
    in your servlet code you can write
    public void doPost(req,resp){
    DefaultHandler handler = new Echo02();
    handler.parse(req.getInputStream());
    Offcourse you will need to modify the code of Echo02 class a bit to suit your requirement which would finally retrun you a string and you can then write it using
    respose.getWriter().write(responseString);

  • Minimum version required to upload and download files using Netweaver Gateway

    What is the minimum service pack required to use the feature of Upload and download files using netweaver gateway. I already have a SP05

    Hi,
    as per this blog How to Read Photo from SAP system using SAP Gateway this should be possible with SP05.
    also refer How To Upload and Download Files Using SAP NW Gateway SP06
    Regards,
    Chandra

  • How to read a file using servlet

    hi ,
    i've to read a file using servlet ,
    should read the file using servlet and display it in JSP,Could anybody get me how can i do it .
    Shiva

    To do that you need to get the response output stream and write yur file contents to that.
    response.setContentType(mimeType); //Set the mime type for the response
    ServletOutputStream sos = resp.getOutputStream();
    sos.write(bytes from your file input stream);
    sos.close();

  • How do i download files using other downloader (like orbit downloader) instead of firefox downloader itself?

    how do i download files using other downloader (like orbit downloader) instead of firefox downloader itself?
    please give me detailed steps to do it
    i have orbit downloader

    I tried it again, and this time when I resumed it lost about 10Mbytes, so I guess this means that the app store downloader saves its data every 10MBytes.
    I will try downloading the whole thing again(XCode4) and just hope that this time I can get the whole download before it decides to wipe out what it has already downloaded.

  • How to download a file using servlet

    I have a problem about downloading a file using a servlet.
    Anybody can help me?
    Thanks

    I am assuming that you want to write a servlet that, when invoked by a user (for instance, through a URL link), will download a file using the "save as" dialog (on Windows, for example) in the user's browser.
    In such a case, all you need to do is get the OutputStream from the response object, set the proper MIME type header, and write the file. Here is an (untested, not even compiled) skeleton.
    public class MyServlet extends HttpServlet {
    protected void doGet (HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException {
    ServletOutputStream out = resp.getOutputStream ();
    resp.setContentType ("application/x-foobar");
    while (/* whatever */) {
    In this loop, you generate your "file's" data.
    You can compute it on the fly, pull it from a database,
    read it from a "real" file, or any other means you can dream up.
    The sample line below just writes some of the data (for example,
    a byte array) to the user's browser via the output stream out.
    out.write (data);
    out.flush ();
    Go to http://java.sun.com/j2ee/sdk_1.3/techdocs/api/index.html
    for the JavaDoc on the classes used.
    Cheers!
    Jerry Oberle

  • Problems showing image file using ShowProperty servlet

    Hi there,
    I´m having problems trying to show an image from the repository using ShowProperty servlet. My node is of type image and my repository is a Library Services enabled repository. When I try to show my node´s binary property "file" the servlet returns the following message "A Primary Property is not defined for Node:...". But checking the node´s ObjectClass I can see that the file property is defined as a primary property. Can somebody help me on this ?
    tks,
    George Earp

    Hi Anders,
    first thanks for trying to help me. Answering your questions in order: I certified myself that the node was saved and checked in using the Portal Administration site. I looked in debug mode and the Node is loaded correctly but the properties aren´t there. I have some more information for you. I decompiled the servlets (ShowBinaryServlet and ShowPropertyServlet). The news are that ShowBinaryServlet is a ShowPropertyServlet´s child that has no additional implementation. Other relevant information is that ShowPropertyServlet implementation gets the Node throught NodeOps object and try to get the binary property with it. But, reading the API and doing tests I could only get my Node properties throught a Virtual Node (see NodeOps Interface part of the API). That´s because my Repository is a managed repository. So, the servlets can´t find the bynary property in my Node because it isn´t there... It is under a VirtualNode... Am I right ? If that´s true I believe I´ll have to implement a solution myself... Too sad... :(
    Message was edited by eduardo.earp at Jan 25, 2005 9:21 AM

  • Download local file using Servlet and JSP

    Hello,
    I will like to use a browser to download file on local system using serlvet and Jsp technology. Does anyone have any idea how to do it?
    Any comment will be appreciate.
    Thanks

    Well you can just put the file in a folder that is accessible to the web server. Then have a link point to that file. That will cause the web browser to download the file.
    hattan

  • Problem with downloading file from FTP server

    Hello all
    I have uploaded a file from an application i developed and i want to download this file from another application. The code is
    public static void FTPcon() throws FtpException{
       String hostname = "my.ftp.server";
       String username = "myusername";
       String password = "mypass";
       Ftp ftp = new Ftp(hostname,username,password);
       ftp.setHostname(hostname);
            ftp.setUsername(username);
            ftp.setPassword(password);
            ftp.connect();
            ftp.setBinary();
            ftp.download("file.dat");
            ftp.disconnect();
    }The error i receive is java.io.FileNotFoundException: public.dat (The system cannot find the file specified) but the file is on the server.
    Thanks in advance for any help

    Cotton thank you for your reply
    Any other sugestions please?The server disagrees. So...
    - the file does not existThe file exists.I checked it with an FTP client program.
    - the file has a different nameThe file name is correct
    - you are connected to the wrong serverI am connecting to the correct server
    - you are in the wrong ftp directoryThe file is placed in the home directory
    - the ftp library you are using is broken (less
    likely)I am using the library from jscape.I dont think is broken because i can upload the file from the first application.
    >
    FTP isn't somehow broken in Java. I use it all the
    time. The problem is something listed above. I would
    check all of the first four if I were you because
    that's most likely where the problem is.Message was edited by:
    flightcaptain

  • Japanese character problem while downloading file to application server

    Hello All,
    We are facing a strange problem while downloading a file to application server when file contains japanese text.
    We are downloading vendor and customer information in a flat file format on application server. When the login language is EN program show ouput in a properly formatted manner.
    When the login language is JA (japanese) program does download file with customer vendor data. I can see the description is japanese language but the formatting is gone for a toss.
    We are facing similar issue with other programs downloading files on the application server.
    I am using OPEN DATASET........ENCODING DEFAULT. and working on unicode enabaled ECC 6.0 system
    Quick help appriciated.
    Thanks!

    Hi
    Sometimes this also happens because of your desktop setting.Make sure that your OS also supports the JAPANESSE language.
    Ask your technical support team to enable them in your desktop.
    Thanks & Regards
    Jyo

  • Downloading files using HttpConnection is very slow

    Hi
    I've written a program which will download files over HTTP protocol using the class HttpConnection. I am connecting to the net using Proxy with authorization. At times it takes long time to download even a 2 MB file, but it works very fast on fewer occasions. The same file If I try to download using browser such as IE or FireFox, download happens in few seconds.
    I am not sure where the problem is. Can anyone guide me on this issue?
    Regards,
    Faisal

    The HTTPUrlConnection do not seem to utilize the
    Connection Keep Alive feature of HTTP so it createa
    seperate connection for each request.Eh? The Sun implementation can utilize HTTP
    Connection Keep Alive if you tell it to, and it also
    runs a connection pool.Great! can you explain a bit how you enable it?
    Can I just do it by setting the Connection: Keep-Alive header

  • Write to existing file using servlets

    Every time I try to read an existing file using my current set of servlets, I get "File cannot be found". I don't understand what the problem is because I'm using the exact same location as the code where I read the document. Is there something else I'm missing? I've tried countless methods of writing, each will compile and such, but all give me the same result (IE nothing). Here's how my horrific code looks right now. Much was taken from the previous code that checks the passwords file.
    Technically, it compiles and runs, but I get "java.io.FileNotFoundException: \WEB-INF\passwords (The system cannot find the path specified)" in the output. The file IS THERE and can be read in my password checking servlet without a problem...
    package hw3Pack;
    import java.io.*;
    import java.util.*;
    import javax.servlet.ServletContext;
    import javax.servlet.ServletException;
    import javax.servlet.http.*;
    public class passCheck extends HttpServlet {
      public void doGet(HttpServletRequest request, HttpServletResponse response)
          throws ServletException, IOException {
            response.setContentType("text/html");
            HttpSession session = request.getSession(true);
            PrintWriter out = response.getWriter();
            try {
                    String filename = "/WEB-INF/passwords";
                    String email = request.getParameter("email");
                    String password = request.getParameter("password");
                    String remember = request.getParameter("remember");
                    ServletContext context = getServletContext();
              FileOutputStream fos = new FileOutputStream(filename);
                    InputStream is = context.getResourceAsStream(filename);
              if (!is.equals(null)) {
                   InputStreamReader isr = new InputStreamReader(is);
                   BufferedReader reader = new BufferedReader(isr);
                   String text = "";
                            } // if (is != null)
                    else {
                    } // else (password not blank)
            finally {
                out.close();
            } // finally
    }

    OK... I feel a bit dumb now... This code was working earlier (the writing part) and now it's not working since I added in the username check portion. It should be essentially complete at this point, I just need to figure out why it no longer writes the file. Any clues or insights?
    I'm about to add a password checker (confirm both passwords entered on registration form are equal) Lets hope I don't mess more up...
    package hw3Pack;
    import java.io.*;
    import java.util.*;
    import javax.servlet.ServletContext;
    import javax.servlet.ServletException;
    import javax.servlet.http.*;
    import java.net.*;
    public class regComplete extends HttpServlet {
      public void doGet(HttpServletRequest request, HttpServletResponse response)
          throws ServletException, IOException {
            response.setContentType("text/html");
            HttpSession session = request.getSession(true);
            PrintWriter out = response.getWriter();
            boolean clear = true;
            try {
                    String email = request.getParameter("email");
                    String password = request.getParameter("password");
                    out.println(email +" and " + password);
                    String filename = "/WEB-INF/passwords";
                    ServletContext context = getServletContext();
                    InputStream is = context.getResourceAsStream(filename);
              if (!is.equals(null)) {
                   InputStreamReader isr = new InputStreamReader(is);
                   BufferedReader reader = new BufferedReader(isr);
                   String text = "";
                            while ((text = reader.readLine()) != null) {              
                                    StringTokenizer st = new StringTokenizer(text, "," );
                                    String getEmail = st.nextToken();
                                    String getPass = st.nextToken();
                                            if (email.equals(getEmail) && !email.equals(null)) {
                                                    clear = false;
                                                    out.println("I'm sorry but that email address is in use.  Please try again.");
                                            } else {
                                            //do nothing
                    if (clear==true) {
                        File file = new File("/WEB-INF/passwords");
                        BufferedWriter writer = new BufferedWriter(new FileWriter(file, true));
                        out.println("going");
                        writer.append("\r\n" +email +"," +password);
                        out.println("Writing");
                        writer.close();
                        } else {
                } // try
            finally {
                out.close();
                } // finally
      }

  • Problem with downloading files!

    Hi, I am using a9300 MTN as my service provider! Lately I cannot download or open any files on the internet! I hav rebooted my phone numerous times and the problem still persists! Cud it be a software issue or is my service provider having trouble with providing internet service to us! Help!! Really getting frustated!!☹
    Solved!
    Go to Solution.

    Hey kgaoza12,
    Welcome to the BlackBerry Support Community Forums.
    Thanks for the question.
    Downloading files from the browser is controlled and throttled by your network service provider.  I suggest you contact them for more information.
    Let me know if you have any more questions.
    Cheers.
    -ViciousFerret
    Come follow your BlackBerry Technical Team on Twitter! @BlackBerryHelp
    Be sure to click Like! for those who have helped you.
    Click  Accept as Solution for posts that have solved your issue(s)!

  • After upgrade from DW8 to DWCS6, 2 problems: uploading/downloading (file structure?)

    Hi,
    I took a big leap and upgraded from DW8 to DWCS6. Also went from MAC G5 PPC to IMAC with Mavericks.
    I transferred my site files over and set up a new site in DWCS6, pointing to the site files. No problem.
    However, I have run across two problems since then.
    1. If I open a file on the local site on the computer, it does not see the images folder. I can navigate to it and re-associate the image, but it is not automatic. I did nothing to change the structure of the local site, except move it as a whole from one computer to another. If I add an additional ../ to the SRC, then it comes up. If I then upload that page, the link still exists correctly. I don't understand the problem at all...please help!
    2. When I want to upload a local file using the put command, I get an error message, something like it cannot create a certain folder in which the file exists. However, that file already exists on the remote end. I can drag the file over and then there is no problem.
    I believe I can see that the problem is the same with both uploading and downloading, but can't quite figure out how to fix it. Any ideas? I figure this is probably common, or at least, I hope it is!
    Thanks in advance,
    Linda

    Wow, thanks so much for the super-fast reply:
    I will attach three images showing what you asked for. When I went back to check I noticed that the local files actually do seem to link up the images...it is only when I bring them down (get them) from the remote site that there is a problem...I'm embarrassed to say that I don't remember it being this way earlier, but since I have done nothing to 'heal it' it might have been....only thing I did do was piece by piece link them up on the pages on which I was working.
    Anyway, here are the screenshots. If you need more, or if they are unclear, let me know.
    I really appreciate your help. If you write back and I do not answer immediately, it is only because I am out for a while.
    Debbie
    #1 /users/Madiba/Documents/Sites/Plumsite
    #2 /Users/Madiba/Documents/Sites/Plumsite/images
    ../../images/DVD2/dvd21001m.jpg

Maybe you are looking for

  • Save As short cut in Pages

    I was as frustrated as many other people it seems when I found Save As had disappeared from the edit menu and replaced with a very convoluted saving system. Luckily I found the short cut for Save As; alt, shift, cmd, s Tricky but doable.

  • Change the attachment name in email via webservice

    Hey, is there any chance to change die filename of attacheted files (reports) using email scheduling? There is no option in the webinterface. We are using the webservice for scheduling - call the scheduleReport method. There is a tag reportDataFileNa

  • Error in MIGO 411K

    Hi GUrus, Can anybody please help me with the following issue. When the user is trying to trasnfer the consignment stock into our own stock using 411K in MIGO, they are getting the following error Deficit of VC Unrestr. prev. 260,630 LB : mat No Plan

  • Closure date for change request

    Hi experts, I've defined a closure date in the date profile for my change requests and i want this date to be automatically populated when the ticket is closed. I've been trying to define a date rule (with ABAP) to set this date to actual date in a p

  • New battery is smaller than old one

    I had the battery replaced due to the recall. The new battery appears to be 'shrinking' and does not sit in the battery compartment very well. Theree is a sharp lip around the edge of the compartment. Has anyone had this issue - especially with a bla