How to download a file from the server using Servlet - java

I am new to servlet technology, i need to write code to download files from the server at client side.
Can we download files diectly from the server using servlet technology?
Please provide the valuable suggestions.

If I understand you correctly, You can download the file from HTTP servlet via response.sendRedirect() for files available in public location.
Else you need to use the response output stream to bind the file information so that it will prompt you to download for a file:
OutputStream out = response.getOutputStream();
FileInputStream in = new FileInputStream(fileToDownload);
byte[] buffer = new byte[4096];
int length;
while ((length = in.read(buffer)) > 0){
out.write(buffer, 0, length);
}
in.close();
out.flush();
I gues you can handle the exceptions, of course.

Related

Is it a good way to download a file from internet using jsoup library?

I am using Jsoup Library for downloading a file from internet. I don't know it's a good way to use Jsoup library to download a file from internet using Jsoup or not (because Jsoup is a HTML parser). I am using the following code to downlaod a file:
final Thread t = new Thread(new Runnable() {
#Override
public void run() {
try {
Connection.Response response = Jsoup.connect("URL")
.ignoreContentType(true)
.execute();
BufferedInputStream inputStream = response.bodyStream();
FileOutputStream fos = new FileOutputStream("location");
byte[] buffer = new byte[1024];
int len;
while((len = inputStream.read(buffer)) != -1){
fos.write(buffer, 0, len);
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
t.start();
Will there be a problem if i use Jsoup library for downloading a file? Thanks.
As you have mentioned yourself , jsoup is a Java library for working with real-world HTML. It provides a very convenient API for extracting and manipulating data, using the best of DOM, CSS, and jquery-like methods.
It might be working for you now, but you might need to add some headers, timeouts etc in near future. Hence it is better to use a HTTPClient to do this job. HTTPClients are meant to make client side HTTP calls, which would do the job better than JSoup.
One such HTTPClient from apache: http://hc.apache.org/httpclient-3.x/

TCP Socket send data in GZIP Compression format

I am sending MultiPart content to my remote server to store it in filesystem. For this I am using Java TCP/IP protocol. For avoiding network bandwidth and TCP Input / Output buffer memory , I am sending the data in GZIP compressed format. But , I cannot decompress the data received from the client. I got Unexpected end of ZLIB input stream Exception. Its due to the server is receiving data in chunks.
Java Code
Client
OutputStream out = new GZIPOutputStream(sock.getOutputStream());
byte[] dataToSend = FileUtil.readFile(new File("/Users/bharathi/Downloads/programming_in_go.pdf"));
out.write(dataToSend);
Server
out = new FileOutputStream("/Users/bharathi/Documents/request_trace.log");
InputStream in = new GZIPInputStream(clntSocket.getInputStream());
int totalBytesRead = 0;
int bytesRead;
byte[] buffer = new byte[BUFFER_SIZE];
while ((bytesRead = in.read(buffer)) != -1)
{
out.write(buffer , 0 , bytesRead);
totalBytesRead += bytesRead;
}
Is there any solution to send the data in GZIP compressed format in Socket?
GZIPOutputStream generates a GZIP file format, meaning that the other end has to receive the complete stream (which is a file) before it can process it, this is the reason for your error.
If you are looking to actually do a stream based data transfer, drop gzip, and go for zlib, I believe Zlib compression Using Deflate and Inflate classes in Java answers how to do this.
Try adding:
out.flush();
sock.shutdownOutput();
to your client code.

writing to a file kept in ftp server

I have a requirement in which I have to write to files kept in FTP server using java ,I cant write to a file in the local server and then transfer it to ftp due to sensitivity of the data,can anyone share some thoughts/links on this.
Any Help will be greatly appreciated.
Apology for not posting my code snippet earlier below is the code I wrote
Student stu=new Student();
stu.setName("xyz");
stu.setRoll("12");
ftpClient.changeWorkingDirectory("/mydirectory/release/");
//abc.txt is the file on the server
FileOutputStream fos=(FileOutputStream)ftpClient.appendFileStream("abc.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(stu);
Iam not getting any exception ,but also not able to write into the file..
yes I want to upload bytes via ftp from memory..
Thanks
I got the solution,I had to use url instead of ftpClient
URL url = new URL("ftp://user:pass#myftp.abc.com/myFile.txt;type=i");
URLConnection urlc = url.openConnection();
OutputStream os = urlc.getOutputStream(); // To upload
OutputStream buffer = new BufferedOutputStream(os);
ObjectOutput output = new ObjectOutputStream(buffer);
output.writeObject(myObject);
buffer.close();
os.close();
output.close();
It looks like Apache's FTPClient class, documented here, will do what you want.

java - Download and then write image as servlet response

How to download an image from a server and then write it as a response in my servlet.
What is the best way to do it keeping good performance?
Here's my code:
JSONObject imageJson;
... //getting my JSON
String imgUrl = imageJson.get("img");
if you don't need to hide your image source and if server is accessible from the client as well, I'd just point your response to remote server (as you already have the url) => you don't need to do a download to your server first, but possibly client could access it directly => you don't waste your resources.
However if you still need to download it to your server first, following post might help: Writing image to servlet response with best performance
It's important to avoid intermediate buffering of image in servlet. Instead just stream whatever was received to the servlet response:
InputStream is = new URL(imgUrl).openStream();
OutputStream os = servletResponse.getOutputStream();
IOUtils.copy(is, os);
is.close();
I'm using IOUtils from Apache Commons (not necessary, but useful).
The complete solution : download a map and save to file.
String imgUrl = "http://maps.googleapis.com/maps/api/staticmap?center=-15.800513,-47.91378&zoom=11&size=200x200&sensor=false";
InputStream is = new URL(imgUrl).openStream();
File archivo = new File("c://temp//mapa.png");
archivo.setWritable(true);
OutputStream output = new FileOutputStream(archivo);
IOUtils.copy(is, output);
IOUtils.closeQuietly(output);
is.close();

Compressing and decompressing streams

I found this article about simple proxy server implemented in JAVA:
http://www.java2s.com/Code/Java/Network-Protocol/Asimpleproxyserver.htm
The code simply gets some stream from the client, after sends it to the server and after it gets stream from the server and sends the response to the client. What I would like to do is to compress this streams before it is sent and decompress after it is received.
I found the class GZIPInputStream but I'm not sure how to use it and what I found on internet didn't help me. I either didn't understand that so much or it was not a good solution for me.
My idea is too that but I'm not sure if its ok:
final InputStream streamFromClient = client.getInputStream();
final OutputStream streamToClient = client.getOutputStream();
final InputStream streamFromServer = server.getInputStream();
final OutputStream streamToServer = server.getOutputStream();
InputStream gzipStream = new GZIPInputStream(streamFromClient );
try
{
while ((bytesRead = gzipStream.read(request)) != -1)
{
streamToServer.write(request, 0, bytesRead);
streamToServer.flush();
}
}
catch (Exception e) {
System.out.println(e);
}
Now the data sent to the server should be compressed before sending (but I'm not sure if it's a correct solution). IS IT?
Now imagine the server sends me the compressed data.
So this stream:
final InputStream streamFromServer = server.getInputStream();
is compressed.
How can I decompress it and write to the
final OutputStream streamToClient = client.getOutputStream();
Thanks for the help, guys!
Read the javadoc of these streams : http://download.oracle.com/javase/6/docs/api/java/util/zip/GZIPInputStream.html and http://download.oracle.com/javase/6/docs/api/java/util/zip/GZIPOutputStream.html.
GZIPOutputStream compresses the bytes you write into it before sending them to the wrapped output stream. GZIPInputStream reads compressed bytes from the wrapped stream and returns uncompressed bytes.
So, if you want to send compressed bytes to anyone, you must write to a GZIPOutputStream. But of course, this will only work if the receiving end knows it and decompresses the bytes it receives.
Similarly, if you want to read compressed bytes, you need to read them from a GZIPInputSTream. But of course, it'll only work if the bytes are indeed compressed using the same algorithm by the sending end.

Categories

Resources