I want to download a file from a Server into a client machine. But i want the file to be downloaded from a browser : I want the file to be saved at the Downloads Folder.
Im using the following code to download files.
public void descarga(String address, String localFileName) {
OutputStream out = null;
URLConnection conn = null;
InputStream in = null;
try {
// Get the URL
URL url = new URL(address);
// Open an output stream to the destination file on our local filesystem
out = new BufferedOutputStream(new FileOutputStream(localFileName));
conn = url.openConnection();
in = conn.getInputStream();
// Get the data
byte[] buffer = new byte[1024];
int numRead;
while ((numRead = in.read(buffer)) != -1) {
out.write(buffer, 0, numRead);
}
// Done! Just clean up and get out
} catch (Exception exception) {
exception.printStackTrace();
} finally {
try {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
} catch (IOException ioe) {
// Shouldn't happen, maybe add some logging here if you are not
// fooling around ;)
}
}
It works but unless i specify the absolute path it does not download the file, therefore is useless to use from different clients with different browsers, because the webpage does not even prompts the message that lets the user know that a file is being downloaded. What can i add to get that to work?
Thanks
Related
This question already has answers here:
Download file from server in java
(2 answers)
Closed 4 years ago.
guys!
I have a problem! I'm trying to download a .zip (size is 150 mb) file from Internet using this code:
public void downloadBuild(String srcURL, String destPath, int bufferSize, JTextArea debugConsole) throws FileNotFoundException, IOException {
debugConsole.append(String.format("**********Start process downloading file. URL: %s**********\n", srcURL));
try {
URL url = new URL(srcURL);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
httpConn.setRequestMethod("POST");
httpConn.connect();
in = httpConn.getInputStream();
out = new FileOutputStream(destPath);
byte buffer[] = new byte[bufferSize];
int c = 0;
while ((c = in.read(buffer)) > 0) {
out.write(buffer, 0, c);
}
out.flush();
debugConsole.append(String.format("**********File. has been dowloaded: Save path is: %s********** \n", destPath));
} catch (IOException e) {
debugConsole.append(String.format("**********Error! File was not downloaded. Detail: %s********** \n", e.toString()));
} finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
}
}
}
but the file is not completely downloaded. (only 4000 bytes). What am I doing wrong?
you can use the following code to download and extract zip file from given uri path.
URL url = new URL(uriPath);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
InputStream in = connection.getInputStream();
ZipInputStream zipIn = new ZipInputStream(in);
ZipEntry entry = zipIn.getNextEntry();
while(entry != null) {
System.out.println(entry.getName());
if (!entry.isDirectory()) {
// if the entry is a file, extracts it
System.out.println("===File===");
} else {
System.out.println("===Directory===");
}
zipIn.closeEntry();
entry = zipIn.getNextEntry();
}
FileOutputStream("example.zip").getChannel().transferFrom(Channels.newChannel(new URL("http://www.example.com/example.zip").openStream()), 0, Long.MAX_VALUE);
Simple one-liner. For more info, read here
I'm putting together some code to download files from an HTTP address in Android. I'd like to support download resumption if the download fails mid way.
The output I get when starting the download, then killing the wifi connection and restarting again several times is the following:
Start size 0
Stop size 12333416
Start size 12333416
Stop size 16058200
Start size 3724784
I cannot understand why after the first resumption, subsequent file size readings of the partially downloaded file do not match.
Thanks in advance!
public void download(String source, String target) throws IOException {
BufferedOutputStream outputStream = null;
InputStream inputStream = null;
try {
File targetFile = new File(target);
currentBytes = targetFile.length();
Log.i(TAG, "Start size " + String.valueOf(currentBytes));
outputStream = new BufferedOutputStream(new FileOutputStream(targetFile));
// create the input stream
URLConnection connection = (new URL(source)).openConnection();
connection.setConnectTimeout(mCoTimeout);
connection.setReadTimeout(mSoTimeout);
inputStream = connection.getInputStream();
inputStream.skip(currentBytes);
// calculate the total bytes
totalBytes = connection.getContentLength();
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) > 0) {
// write the bytes to file
outputStream.write(buffer, 0, bytesRead);
outputStream.flush();
currentBytes += bytesRead;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (outputStream != null) {
// close the output stream
outputStream.flush();
outputStream.close();
}
if (inputStream != null) {
// close the input stream
inputStream.close();
}
Log.i(TAG, "Stop size " + String.valueOf(currentBytes));
}
}
There are two things you are doing wrong:
To resume download to file you should append, not rewrite the file. Use special constructor for output stream:
FileOutputStream(targetFile, true)
To request part of file from server you should use HTTP 1.1 property "Range". You can do it like this:
HttpURLConnection httpConnection = (HttpURLConnection) connection;
connection.setRequestProperty("Range", "bytes=" + currentBytes + "-");
I have a web server that stores the files at http://user.mysite.com/content
Now all I want to achieve in my android application is to download every files that user can upload on this server, I have created function in android that can download files and stores it into sdcard which is something like this:
public void doDownload(){
try {
int count;
URL url = new URL("http://user.mysite.com/content");
URLConnection connection = url.openConnection();
connection.connect();
int lengthOfFile = connection.getContentLength();
long total = 0;
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(f);
byte data[] = new byte[1024];
while ((count = input.read(data)) != -1) {
total += count;
publishProgress((int)(total/1024),lengthOfFile/1024);
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
}
catch (Exception e) {
Log.e("Download Error: ", e.toString());
}
}
How can I retrive the list of files on server and URL for those files + name of files and download Each one of them on to app using loop?
To get the list of file I have some thing list this:
public List clientServerFileList(){
URL url;
List serverDir = null;
try {
url = new URL("http://user.mysite.com/content/");
ApacheURLLister lister = new ApacheURLLister();
serverDir = lister.listAll(url);
}
catch (Exception e) {
e.printStackTrace();
Log.e("ERROR ON GETTING FILE","Error is " +e);
}
System.out.println(serverDir);
return serverDir;
}
My server is: Apache/2.2.24 (Unix) mod_ssl/2.2.24 OpenSSL/1.0.0-fips mod_auth_passthrough/2.1 mod_bwlimited/1.4 FrontPage/5.0.2.2635 Server at user.mysite.com Port 80
Send a POST or GET request to your server. When your server recive this request, response the JSON or XML to the client.
Parse the XML or JSON that server response to you, get the filename and ..., you can download the file in the file list.
I am trying to Post a .txt file to a local tomcat webserver that i have on my system.
But when i try to do a post then i get a Error: Not Found.
The source file is present but even after that i get this error.
Can you please let me know what i am doing wrong here. i have pasted my code below.
File file = new File("C:\\xyz\\test.txt");
URL url = new URL("http://localhost:8080/process/files");
urlconnection = (HttpURLConnection) url.openConnection();
urlconnection.setDoOutput(true);
urlconnection.setDoInput(true);
urlconnection.setRequestMethod("POST");
BufferedOutputStream bos = new BufferedOutputStream(urlconnection.getOutputStream());
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
int i; // read byte by byte until end of stream
while ((i = bis.read()) >0) {
bos.write(i);
}
bos.close();
System.out.println(((HttpURLConnection)urlconnection).getResponseMessage());
} catch(Exception ae)
{
ae.printStackTrace();
}
try {
InputStream inputStream;
int responseCode=((HttpURLConnection)urlconnection).getResponseCode();
if ((responseCode>= 200) &&(responseCode<=202) ) {
inputStream = ((HttpURLConnection)urlconnection).getInputStream();
int j;
while ((j = inputStream.read()) >0) {
System.out.println("------ TESTING ------");
}
} else {
inputStream = ((HttpURLConnection)urlconnection).getErrorStream();
}
((HttpURLConnection)urlconnection).disconnect();
} catch (IOException e) { // TODO Auto-generated catch block
e.printStackTrace();
}
}
Can you please let me know what is going wrong here.
I am scratching my head on this for a long time now.
Thanks
Vikeng
The URL you are POSTing to needs to point to a servlet or something similar. You cannot upload a file to a directory just by sending a POST request--the POST request has to be handled by something.
what I want ask is could I do something with file? which Stream is file send by ?Should file change to another data?
You can read the file using an InputStream and write its data to the OutputStream of a Socket.
This may look something like this:
OutputStream out = null;
FileInputStream in = null;
try {
// Input from file
String pathname = "path/to/file.dat";
File file = new File(pathname);
in = new FileInputStream(file);
// Output to socket
String host = "10.0.1.8";
int port = 6077;
Socket socket = new Socket(host, port);
socket.connect(endpoint); // TODO: define endpoint
out = socket.getOutputStream();
// Transfer
while (in.available() > 0) {
out.write(in.read());
}
} catch (Exception e) {
// TODO: handle exception
} finally {
if (out != null)
out.close();
if (in != null)
in.close();
}
PS: I'm not sure if this actually works. It's meant to get you started...