Monday, May 11, 2009

Download the image from Servlet usign core java code

For download the image from Servlet usign core java code
import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

public class Download {

public static void main(String args[]) throws Exception {
String url = "http://localhost:9080/mYWebApp/sendImage/Fashion/shirt.jpg";
URL u = new URL(url);
URLConnection uc = u.openConnection();
String contentType = uc.getContentType();
int contentLength = uc.getContentLength();
if (contentType.startsWith("text/")|| contentLength == -1) {
throw new IOException("This is not a binary file.");
}
InputStream raw = uc.getInputStream();
InputStream in = new BufferedInputStream(raw);
byte[] data = new byte[contentLength];
int bytesRead = 0;
int offset = 0;
while (offset < contentLength) {
bytesRead = in.read(data, offset, data.length - offset);
if (bytesRead == -1)
break;
offset += bytesRead;
}
in.close();

if (offset != contentLength) {
throw new IOException("Only read " + offset + " bytes; Expected " + contentLength + " bytes");
}

System.out.println("DATA :: "+u.getFile());
String filename = u.getFile().substring(u.getFile().lastIndexOf('/') + 1);
System.out.println("FILE NAME :: "+filename);
FileOutputStream out = new FileOutputStream(filename);
out.write(data);
out.flush();
out.close();
}
}

No comments:

Post a Comment

Please leave your feedback or your question related to this blog. :)