Kanchan Ruia
Kanchan Ruia

Reputation: 327

java code to download an image from server to client

I am a new to Java, I don't know much about it.

I am developing a web application, in which I have an option to download an image. If user clicks, he should be able to download image from server to client side (say, at location C:/).

I have implemented this code ::

import java.awt.Image;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import javax.imageio.ImageIO;

public class DownloadingImages {

    public DownloadingImages() {}
    
    public void download(String name) throws MalformedURLException, IOException {

        Image image = null;
        try {
            //URL url = new URL("file:///E:/myproject/build/web/images/Webcam.jpg");
            String spath = "http://localhost:5051/marketpoint/images/";
            String cpath = "C:\\";

            spath = spath + name ;
            cpath = cpath + name ;
            System.out.println("FULL path::: "+spath);
 
            URL url = new URL(spath);

            InputStream in = new BufferedInputStream(url.openStream());
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            byte[] buf = new byte[1024];
            int n = 0;
            while (-1!=(n=in.read(buf)))
            {
               out.write(buf, 0, n);
            }
            out.close();
            in.close();
            byte[] response = out.toByteArray();
            FileOutputStream fos = new FileOutputStream(cpath);
            fos.write(response);
            fos.close();  
        } catch (IOException e) {
        
        }
    }
}

(name = name of the image that the client wants to download.)

The problem is that the image gets downloaded on the server's side, not the client (At C:/). Can anybody please tell where am I going wrong.

For this I am using NetBeans as my editor, Apache Tomcat as my server. Both client and server connect through port 5051. And the image that the client wants to download from the server is a simple JPG image.

Upvotes: 1

Views: 9109

Answers (3)

gashu
gashu

Reputation: 492

Please try this working code first:

package com.ashugupt.github.stackover;

import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class URLTest {

  private static void sendGet() throws Exception {

    String url = "http://www.uni-koblenz-landau.de/images/starts-c-ko.jpg";
    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();

    // optional default is GET
    con.setRequestMethod("GET");

    //add request header
    con.setRequestProperty("User-Agent", "Mozilla/5.0");

    int responseCode = con.getResponseCode();
    System.out.println("\nSending 'GET' request to URL : " + url);
    System.out.println("Response Code : " + responseCode);

    InputStream in = con.getInputStream();
    OutputStream out = new FileOutputStream("/Users/ravikiran/Desktop/abc.jpg");
    try {
      byte[] bytes = new byte[2048];
      int length;

      while ((length = in.read(bytes)) != -1) {
        out.write(bytes, 0, length);
      }
    } finally {
      in.close();
      out.close();
    }
  }

  public static void main(String[] args) throws Exception {
    sendGet();
  }
}

Upvotes: -1

Sagar Bhosale
Sagar Bhosale

Reputation: 405

Try this running code.It will help you.

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Authenticator;
import java.net.PasswordAuthentication;
import java.net.URL;

public class SaveImageFromUrl {

    public static void main(String[] args) throws Exception {



        String imageUrl = "http://2.bp.blogspot.com/_GHaEnqqbRsE/SVsxi-gdQ2I/AAAAAAAAAAU/NS6MEejoHtE/s320/Gppfront.jpg";


        String destinationFile = "D://gpp.jpg";

        saveImage(imageUrl, destinationFile);
    }

    public static void saveImage(String imageUrl, String destinationFile) throws IOException {
        URL url = new URL(imageUrl);
        InputStream is = url.openStream();
        OutputStream os = new FileOutputStream(destinationFile);

        byte[] b = new byte[2048];
        int length;

        while ((length = is.read(b)) != -1) {
            os.write(b, 0, length);
        }

        is.close();
        os.close();
    }

}

Upvotes: -1

Jon7
Jon7

Reputation: 7225

If the file is getting downloaded to C:\, then that's what your cpath variable equals when you open your FileOutputStream. This would imply that your name variable is being passed in as an empty string. Try putting in some logging statements (or even better, using the netbeans debugger!) to see what values your variables are holding as your code executes.

EDIT: I think I understand the problem now. You're running this as a servlet or something similar. That means that your code is executing on the server, rather than the client. If you want to download the file to a specific path on the client, you're going to have to use an Applet or something similar that runs on the client side. Alternatively, you can return the file in the HTTP response and the user's browser will ask them where to save the file. Although, at that point, the user could just navigate to the jpg in a browser themselves.

You might want to explain your use case in more detail if this doesn't answer your question.

Upvotes: 1

Related Questions