how to download image / files from ftp server via url in android? - java

private String ftpUrl = "ftp://%s:%s#%s/%s;";
private static String host = "www.krishnas.com.np";
private static String user = "tryagn#krishnas.com.np";
private static String pass = "technology_krixnas";
private static String filePath = "112.jpg";
private static String savePath =
Environment.getExternalStorageDirectory() + "/" +
Environment.DIRECTORY_DCIM +"/abe.jpg";
My doInBackground() in asynctask is:
protected String doInBackground(String... f_url) {
int count;
try {
ftpUrl = String.format(ftpUrl, user, pass, host, filePath);
//System.out.println("URL: " + ftpUrl)
Log.d("-----------", ""+ftpUrl);
// try {
//URL url = new URL(ftpUrl);
//URLConnection conn = url.openConnection();
// InputStream inputStream = conn.getInputStream();
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.connect();
// this will be useful so that you can show a tipical 0-100% progress bar
int lenghtOfFile = conection.getContentLength();
// download the file
InputStream input = new BufferedInputStream(url.openStream(), 8192);
// Output stream
OutputStream output = new FileOutputStream(savePath);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
i=(int)((total*100)/lenghtOfFile);
publishProgress(""+(int)((total*100)/lenghtOfFile));
// i = (int)((total*100)/lenghtOfFile);
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// c
// losing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
I want to download a file/image from my FTP server, it shows image in link but does not download in internal storage. I am learning ftp server downloader not the http request!! Don't know where it goes wrong??

You are using external storage to store file Environment.getExternalStorageDirectory()
So if you want to store it in internal storage,
You can use getFilesDir() or getCacheDir():
File file = new File(context.getFilesDir(), filename);
For more Information refer this link:

Related

Downloaded files with whitespaces in path are damaged

I have following problem. I have to download pdf files from a server and some of them have whitespaces in their names. So every file will be downloaded, but those, which have whitespaces can not be opened.
If I access this files on the server via chrome, they open well (also with the whitespace in the url).
And what I am wondering about is, that java says the files will be downloaded. But when I try to open them in Acrobat Reader, it shows me an error message, that the files are damaged. Here is the sample of my code:
public static void downloadFile(String fileURL, String saveDir) throws IOException {
Authenticator.setDefault(new Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("*****", "*********".toCharArray());
}
});
final int BUFFER_SIZE = 4096;
URL url = new URL(fileURL);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
String credentials = "ptt" + ":" + "ptt123";
String encoding = Base64.getEncoder().encodeToString(credentials.getBytes(StandardCharsets.UTF_8));
httpConn.setRequestProperty("Authorization", String.format("Basic %s", encoding));
int responseCode = 0;
responseCode = httpConn.getResponseCode();
// always check HTTP response code first
if (responseCode == HttpURLConnection.HTTP_OK) {
String fileName = "";
String disposition = httpConn.getHeaderField("Content-Disposition");
String contentType = httpConn.getContentType();
int contentLength = httpConn.getContentLength();
if (disposition != null) {
// extracts file name from header field
int index = disposition.indexOf("filename=");
if (index > 0) {
fileName = disposition.substring(index + 10,
disposition.length() - 1);
}
} else {
// extracts file name from URL
fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1,
fileURL.length());
}
// opens input stream from the HTTP connection
InputStream inputStream = httpConn.getInputStream();
String saveFilePath = saveDir + File.separator + fileName;
// opens an output stream to save into file
FileOutputStream outputStream = new FileOutputStream(saveFilePath);
int bytesRead = -1;
byte[] buffer = new byte[BUFFER_SIZE];
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
inputStream.close();
System.out.println("File downloaded");
} else {
System.out.println("No file to download. Server replied HTTP code: " + responseCode);
}
httpConn.disconnect();
}
I also tried to replace the whitespace through "%20" in the fileUrl.
So what can be the problem? As I wrote above, the files without any whitespace can be opened after the the download without any problems.
I use Java 1.7.
Cheers,
Andrej
if fileName contains space then replace it to some other charecter. it may work, if not please let me know.
if(fileName.trim().contains(" "))
fileName.replace(" ","_");
URL url = new URL(URLEncoder.encode(fileUrl, "UTF-8"));

Video is not downloading from a URL

i want to download video from URL my function is as below
String fileURL = "http://192.168.1.2/UserFiles/Videos/OutputVideo/Birthday%20Bash5tV3fgjf4Sfi11sC.mp4";
String fileName = "Abc.mp4";
public void downloadFile(String fileURL, String fileName){
Toast.makeText(getApplicationContext(), "Download File", Toast.LENGTH_LONG).show();
try
{
URL u = new URL(fileURL);
URLConnection ucon = u.openConnection();
//Define InputStreams to read from the URLConnection.
// uses 3KB download buffer
File file =new File(Environment.getExternalStorageDirectory() + File.separator + "/Planetskool/Media/Videos/"+fileName);
InputStream is = ucon.getInputStream();
BufferedInputStream inStream = new BufferedInputStream(is, 1024 * 5);
FileOutputStream outStream = new FileOutputStream(file);
byte[] buff = new byte[5 * 1024];
//Read bytes (and store them) until there is nothing more to read(-1)
int len;
while ((len = inStream.read(buff)) != -1)
{
outStream.write(buff,0,len);
}
//clean up
outStream.flush();
outStream.close();
inStream.close();
}
catch (Exception se)
{
se.printStackTrace();
}
}
its downloading video in 0kb whats wrong with this
use async method to download file from URL.
Three things might be happened
Missing Internet permission
Missing Write external storage permission
"/Planetskool/Media/Videos/" Directory not exist, Create dir first.
http://192.168.1.2 it is not internet URL check your URL

Android Webview app not downloading successful

My Android app has a Webview to access to my website. I noticed in the server that when a file is downloaded by the app the bandwidth used is less than when is downloaded by another device or browser.
In method onDownloadStart I call to an AsyncTask class:
protected String doInBackground(String... sUrl) {
try {
URL url = new URL(sUrl[0]);
//Getting directory to store the file
//Connection handler
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.connect();
//Obtaining filename
File outputFile = new File(directory, filename);
InputStream input = new BufferedInputStream(connection.getInputStream());
OutputStream output = new FileOutputStream(outputFile);
byte buffer[] = new byte[1024];
int bufferLength = 0;
int total = 0;
while ((bufferLength=input.read(buffer))!=-1) {
total += bufferLength;
output.write(buffer, 0, bufferLength);
}
connection.disconnect();
output.flush();
output.close();
input.close();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
Files downloaded are empty altough their filename and format are correct and I receive HTTP 200 message from the server; also execution does not enter into the while loop. I have tried to change buffer size and the problem is not solved.

Downloading mp3 with meta data/properties such as title, artists and etc

I have the following code. Everything works fine except that the downloded MP3 file does not have any property (metadata) such as Artist, title and etc when I play using the default music player. If tried to download the same mp3 file from the site directly using android browser and play using the default music player, all the metatdata are intact (ie. music player display title, artist and etc).
#Override
protected String doInBackground(String... aurl) {
int count;
i = Integer.parseInt(aurl[0]);
try {
sura = "abc.mp3";
String addr = "http://www.xyzabc.com/" + sura;
URL url = new URL(addr);
HttpURLConnection conexion = (HttpURLConnection) url.openConnection();
conexion.setRequestMethod("GET");
conexion.setDoOutput(true);
conexion.connect();
int lenghtOfFile = conexion.getContentLength();
InputStream input = new BufferedInputStream(url.openStream());
File file = new File(rootDir + "/mysite/" + sura);
OutputStream output = new FileOutputStream(file);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1 & run == true) {
total += count;
publishProgress("" + (int) ((total * 100) / lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
}
return null;
}
The System content provider didn't update as soon as your downloading complete.
Try restart your emulator or install/unstall your sd card, see if the content provider updates.
The uri is MediaStore.Audio.Media.EXTERNAL_CONTENT_URI and you can get details by query MediaStore.Audio.Media.DATA, MediaStore.Audio.Media.TITLE,
MediaStore.Audio.Media.COMPOSER, MediaStore.Audio.Media.ALBUM,
MediaStore.Audio.Media.ARTIST and others (All in MediaStore.Audio.Media.*)
If you want to get the information immediately, maybe you should update the Content Provider manual by yourself.

Updating progress dialog

I am trying to make an application that can help me to evaluate the time to download the file from a web resource. I have found 2 samples:
Download a file with Android, and showing the progress in a ProgressDialog
and
http://www.helloandroid.com/tutorials/how-download-fileimage-url-your-device
The second example shows a smaller download time, but I cannot understand how to update progress dialog using it. I think something should be done with "while" expression in second case, but I cannot find what. Could someone give me any piece of advice?
UPD:
1st code:
try {
time1 = System.currentTimeMillis();
URL url = new URL(path);
URLConnection conexion = url.openConnection();
conexion.connect();
// this will be useful so that you can show a tipical 0-100% progress bar
int lenghtOfFile = conexion.getContentLength();
// downlod the file
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream("/sdcard/analyzer/test.jpg");
byte data[] = new byte[1024];
long total = 0;
time11 = System.currentTimeMillis();
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
publishProgress((int)(total*100/lenghtOfFile));
output.write(data, 0, count);
}
time22= System.currentTimeMillis()-time11;
output.flush();
output.close();
input.close();
} catch (Exception e) {}
timetaken = System.currentTimeMillis() - time1;
2nd code:
long time1 = System.currentTimeMillis();
DownloadFromUrl(path, "test.jpg");
long timetaken = System.currentTimeMillis() - time1;
Where
public void DownloadFromUrl(String imageURL, String fileName) { //this is the downloader method
try {
URL url = new URL(imageURL); //you can write here any link
File file = new File(fileName);
/*Open a connection to that URL. */
URLConnection ucon = url.openConnection();
/*
* Define InputStreams to read from the URLConnection.
*/
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
/*
* Read bytes to the Buffer until there is nothing more to read(-1).
*/
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
/* Convert the Bytes read to a String. */
FileOutputStream fos = new FileOutputStream(PATH+file);
fos.write(baf.toByteArray());
fos.close();
} catch (IOException e) {
Log.d("ImageManager", "Error: " + e);
}
So the thing is that first method seems to be slower for about 30%.
The second example may run faster, but it monopolizes the GUI thread. The first approach, using AsyncTask, is better; it allows the GUI to stay responsive as the download proceeds.
I found it helpful to compare AsyncTask with SwingWorker, as shown in this example.
first link is best. But i can't provide code( it's home comp) in monday or later i can provide full function. But :
private class DownloadFile extends AsyncTask<String, Integer, String>{
#Override
protected String doInBackground(String... url) {
int count;
try {
URL url = new URL(url[0]);
URLConnection conexion = url.openConnection();
conexion.connect();
// this will be useful so that you can show a tipical 0-100% progress bar
int lenghtOfFile = conexion.getContentLength();
// downlod the file
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream("/sdcard/somewhere/nameofthefile.ext");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
publishProgress((int)(total*100/lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {}
return null;
}
this class are best for it ( imho) . publishProgress it's simple function where u have max two lines. Set max and set current. How u can see in this code lenghtOfFile it's how many bytes have ur file. total-current progress ( example 25 from 100 bytes) . Run this class easy : DownloadFile a = new DownloadFile(); a.execute(value,value);//or null if u not using value. Hope u understand me , im not good speaking on english.

Categories