I have a code to download a video from my server and save it in the sd card. I use this code:
String videoURL = "http://www.myapp.com" + key + "/"+key+".avi";
String PATHSdcard = getSDFile();
try {
//set the download URL, a url that points to a file on the internet
//this is the file to be downloaded
URL url = new URL(videoURL);
//create the new connection
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
//set up some things on the connection
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
//and connect!
urlConnection.connect();
//set the path where we want to save the file
//in this case, going to save it on the root directory of the
//sd card.
File SDCardRoot = Environment.getExternalStorageDirectory();
//create a new file, specifying the path, and the filename
//which we want to save the file as.
File file = new File(PATHSdcard,key+".avi");
//this will be used to write the downloaded data into the file we created
FileOutputStream fileOutput = new FileOutputStream(file);
//this will be used in reading the data from the internet
InputStream inputStream = urlConnection.getInputStream();
//create a buffer...
byte[] buffer = new byte[1024];
int bufferLength = 0; //used to store a temporary size of the buffer
//now, read through the input buffer and write the contents to the file
while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
//add the data in the buffer to the file in the file output stream (the file on the sd card
fileOutput.write(buffer, 0, bufferLength);
}
//close the output stream when done
fileOutput.flush();
fileOutput.close();
sendBroadcast (
new Intent(Intent.ACTION_MEDIA_MOUNTED,
Uri.parse("file://" + Environment.getExternalStorageDirectory()))
);
//catch some possible errors...
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
I download it correctly, but I can't play the video after downloaded it.
If I close my application and open again, the video works fine. Any solution?
Thanks in advance
Ensure you have the correct permissions to write to the file. In your manifest file, include this line
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />.
UPDATED:
I am not sure what problem in your code, but can you try my code, maybe it will work:
public void DownloadFromUrl(String DownloadUrl, String fileName) {
try {
File root = android.os.Environment.getExternalStorageDirectory();
File dir = new File (root.getAbsolutePath() + "/your_downloads");
if(dir.exists()==false) {
dir.mkdirs();
}
URL url = new URL(DownloadUrl); //you can write here any link
File file = new File(dir, 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(5000);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
/* Convert the Bytes read to a String. */
FileOutputStream fos = new FileOutputStream(file);
fos.write(baf.toByteArray());
fos.flush();
fos.close();
} catch (IOException e) {
Log.d("DownloadManager", "Error: " + e);
}
}
Related
I Want to download text file from server in private folder, that should not be accessible to user. In short I want to store that file in Application Folder only, not on memory card/internal memory. Once download complete I would like to show the text file in text view. If the file is already downloaded or present in folder, then just want to show that file contents. Can someone help me please? Thanks in Advance.
Here is the code -
url = new URL("https://tmpfiles.org/dl/11433/baby_shark_dodo.txt");
connection = (HttpURLConnection)url.openConnection();
connection.setDoOutput(true);
connection.connect();
connection.setRequestMethod("GET");
try {
File mydir = getApplicationContext().getDir("Songs", Context.MODE_PRIVATE);
if(!mydir.exists()){
mydir.mkdir();
}
final File file = new File(mydir,"Test.txt");
FileOutputStream fileOutputStream = new FileOutputStream(file);
InputStream inputStream = connection.getInputStream();
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
fileOutputStream.write(buffer, 0, bufferLength);
}
fileOutputStream.close();
connection.disconnect();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
I've written the following code to download a file from an url to the external memory in Android application works perfectly.
Now i want to add check authorization before getting its access,how to do this ?
When i enter the url in browser,it asks for username and password
URL url = null;
try {
url = new URL("http://192.168.0.1:4040/usb_dev/usb_a1/New%20folder/ebook-%20sql_serve.doc");
//create the new connection
HttpURLConnection urlConnection = null;
urlConnection = (HttpURLConnection) url.openConnection();
//set up some things on the connection
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
//and connect!
//String basicAuth = "Basic " + new String(Base64.encode("admin:".getBytes(), Base64.NO_WRAP ));
// urlConnection.setRequestProperty ("Authorization", basicAuth);
// urlConnection.setConnectTimeout(30000);
// urlConnection.setReadTimeout(30000);
urlConnection.connect();
//set the path where we want to save the file
//in this case, going to save it on the root directory of the
//sd card.
File SDCardRoot = Environment.getExternalStorageDirectory();
//create a new file, specifying the path, and the filename
//which we want to save the file as.
File file = new File(SDCardRoot,"sql.doc");
//this will be used to write the downloaded data into the file we created
FileOutputStream fileOutput = null;
fileOutput = new FileOutputStream(file);
//this will be used in reading the data from the internet
InputStream inputStream = null;
inputStream = urlConnection.getInputStream();
//this is the total size of the file
int totalSize = urlConnection.getContentLength();
//variable to store total downloaded bytes
int downloadedSize = 0;
//create a buffer...
byte[] buffer = new byte[1024];
int bufferLength = 0; //used to store a temporary size of the buffer
//now, read through the input buffer and write the contents to the file
while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
//add the data in the buffer to the file in the file output stream (the file on the sd card
fileOutput.write(buffer, 0, bufferLength);
//add up the size so we know how much is downloaded
downloadedSize += bufferLength;
//this is where you would do something to report the prgress, like this maybe
// updateProgress(downloadedSize, totalSize);
}
//close the output stream when done
fileOutput.close();
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (ProtocolException e1) {
e1.printStackTrace();
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}catch (IOException e1) {
e1.printStackTrace();
}
I have a URL(http://xxx.xxx/api/getFiles) which is returning a JSON response. According to the developer of the API, this link also return files (images, pdf, word, excel, video, etc) that we're going to download to our Android device.
This link returns a file path (e.g. "/File Folder/") and file name (e.g. "Penguins.jpg") that will be used to link the file to the web server but I don't have an idea how to do it.
Are there ways to download it using this API?
JSON response:
{
"status":"success",
"count":1,
"files":[
{
"file_code":"2",
"file_name":"Penguins.jpg",
"file_type":".jpg",
"file_path”:”\/File Folder\/“
}
]
}
To download file from url following peice of code can help you:
This code will create connection with url server and download it to specified path:
int downloadedSize = 0;
int totalSize = 0;
try {
URL url = new URL("download file url");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
//connect
urlConnection.connect();
//set the path where we want to save the file
File SDCardRoot = Environment.getExternalStorageDirectory();
//create a new file, to save the downloaded file
File file = new File(SDCardRoot, "DownloadFileNameWithExtension"); // like test.png
FileOutputStream fileOutput = new FileOutputStream(file);
//Stream used for reading the data from the internet
InputStream inputStream = urlConnection.getInputStream();
//this is the total size of the file which we are downloading
totalSize = urlConnection.getContentLength();
//create a buffer...
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ((bufferLength = inputStream.read(buffer)) > 0) {
fileOutput.write(buffer, 0, bufferLength);
downloadedSize += bufferLength;
}
//close the output stream when complete //
fileOutput.close();
} catch (final MalformedURLException e) {
e.printStackTrace();
} catch (final IOException e) {
e.printStackTrace();
} catch (final Exception e) {
e.printStackTrace();
}
Don't forget to add Internet permission in your manifest:D
I'm making a android library app that can download and show special files. now I need to write a service that download file in background! are there samples for services?
and I want to save files in SD, because users can update app and don't should miss downloaded files.
If you have a suggest or opinion for this, write me, please.
try {
URL url = new URL("url from apk file is to be downloaded");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.connect();
File sdcard = Environment.getExternalStorageDirectory();
File file = new File(sdcard, "filename.ext");
FileOutputStream fileOutput = new FileOutputStream(file);
InputStream inputStream = urlConnection.getInputStream();
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
fileOutput.write(buffer, 0, bufferLength);
}
fileOutput.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Permission: To write to external storage, you need to add this permission:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Note: you can use above code to get the file downloaded and saved in the SD card. You can run this code in background using AsysnTask or thread.
This is another sample:
try {
//set the download URL, a url that points to a file on the internet
//this is the file to be downloaded
URL url = new URL("http://somewhere.com/some/webhosted/file");
//create the new connection
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
//set up some things on the connection
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
//and connect!
urlConnection.connect();
//set the path where we want to save the file
//in this case, going to save it on the root directory of the
//sd card.
File SDCardRoot = Environment.getExternalStorageDirectory();
//create a new file, specifying the path, and the filename
//which we want to save the file as.
File file = new File(SDCardRoot,"somefile.ext");
//this will be used to write the downloaded data into the file we created
FileOutputStream fileOutput = new FileOutputStream(file);
//this will be used in reading the data from the internet
InputStream inputStream = urlConnection.getInputStream();
//this is the total size of the file
int totalSize = urlConnection.getContentLength();
//variable to store total downloaded bytes
int downloadedSize = 0;
//create a buffer...
byte[] buffer = new byte[1024];
int bufferLength = 0; //used to store a temporary size of the buffer
//now, read through the input buffer and write the contents to the file
while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
//add the data in the buffer to the file in the file output stream (the file on the sd card
fileOutput.write(buffer, 0, bufferLength);
//add up the size so we know how much is downloaded
downloadedSize += bufferLength;
//this is where you would do something to report the prgress, like this maybe
updateProgress(downloadedSize, totalSize);
}
//close the output stream when done
fileOutput.close();
//catch some possible errors...
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
how can i download audio file from server by url and save it to sdcard.
i am using the code below:
public void uploadPithyFromServer(String imageURL, String fileName) {
try {
URL url = new URL(GlobalConfig.AppUrl + imageURL);
File file = new File(fileName);
Log.d("ImageManager", "download begining");
Log.d("ImageManager", "download url:" + url);
Log.d("ImageManager", "downloaded file name:" + fileName);
/* Open a connection to that URL. */
URLConnection con = url.openConnection();
InputStream is = con.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is, 1024 * 50);
FileOutputStream fos = new FileOutputStream("/sdcard/" + file);
byte[] buffer = new byte[1024 * 50];
int current = 0;
while ((current = bis.read(buffer)) != -1) {
fos.write(buffer, 0, current);
}
fos.flush();
fos.close();
bis.close();
} catch (IOException e) {
Log.d("ImageManager", "Error: " + e);
}
}
the above code is not downloading audio file.
if use any permission in menifest file plz tell me.. (i have used internet permission)
please help
thanks..
you must also add
android.permission.WRITE_EXTERNAL_STORAGE
permission if you wish to write data to sd card.
also post your logcat output , if you are getting any IOExceptions.
Your example does not specify a request method and some mimetypes and stuff.
Here you will find a list of mimetypes http://www.webmaster-toolkit.com/mime-types.shtml
Find the mimetypes relevant to you and add it to the mimetypes specified below in the code.
Oh and btw, the below is normal Java code. You'll have to replace the bit that stores the file on the sdcard. dont have an emulator or phone to test that part at the moment
Also see the docs for storage permissions on sd here: http://developer.android.com/reference/android/Manifest.permission_group.html#STORAGE
public static void downloadFile(String hostUrl, String filename)
{
try {
File file = new File(filename);
URL server = new URL(hostUrl + file.getName());
HttpURLConnection connection = (HttpURLConnection)server.openConnection();
connection.setRequestMethod("GET");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.addRequestProperty("Accept","image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/msword, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/x-shockwave-flash, */*");
connection.addRequestProperty("Accept-Language", "en-us,zh-cn;q=0.5");
connection.addRequestProperty("Accept-Encoding", "gzip, deflate");
connection.connect();
InputStream is = connection.getInputStream();
OutputStream os = new FileOutputStream("c:/temp/" + file.getName());
byte[] buffer = new byte[1024];
int byteReaded = is.read(buffer);
while(byteReaded != -1)
{
os.write(buffer,0,byteReaded);
byteReaded = is.read(buffer);
}
os.close();
} catch (IOException e) {
e.printStackTrace();
}
Then call,
downloadFile("http://localhost/images/bullets/", "bullet_green.gif" );
EDIT:
Bad coder me.
Wrap that input InputStream in a BufferedInputStream. No need to specify buffersizes ect.
Defaults are good.