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.
Related
This is my json data coming from backend. How to read this Pdf file using Retofit library.
Thanks in Advance
{
"data": [
{
"Invoice": "Bhavdip-html-to-pdf (1).pdf"
}
]
}
You must first Download your pdf file with
Download Manager
after it, u can use this library for read it.
Library for read pdf in java
Notice :
you must take a url of your pdf in json
see
https://www.codexpedia.com/android/android-download-large-file-using-retrofit-streaming/
this is not a good scenario for large files .if your files are small you can use retrofit for downloading them but if your files are large you should use download manager for them.
above link help you for downloading file with retrofit.
URL url = new URL( f_url[0] );//pass you url here
URLConnection conection = url.openConnection();
conection.connect();
// getting file length
int lenghtOfFile = conection.getContentLength();
// input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream( url.openStream(), 1024 );
// Output stream to write file
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File folder = new File( extStorageDirectory );
String timeStamp = new SimpleDateFormat( "yyyyMMdd_HHmmss", Locale.getDefault() ).format( new Date() );
String fileName = "SMART_" + timeStamp + "_" + Brochure.substring( Brochure.lastIndexOf( '/' ) + 1 );
File file = new File( folder, fileName );
try {
file.createNewFile();
} catch (IOException e1) {
e1.printStackTrace();
}
OutputStream output = new FileOutputStream( file);
byte[] data = new byte[1024];
long total = 0;
while ((read( data )) != -1) {
// writing data to file
output.write( data, 0, count );
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e( "Error: ", e.getMessage() );
}
this is the way of download pdf file from the server
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 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);
}
}
I am trying to cache of videos by this
try {
URL oracle = new URL(url);
URLConnection yc = oracle.openConnection();
InputStream in = yc.getInputStream();
File file = new File(getApplicationContext().getCacheDir() ,url);
if(!file.exists()){
file.setReadable(true);
file.createNewFile();
if (file.canWrite()){
FileOutputStream out = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int len1 = 0;
while ( (len1 = in.read(buffer)) > 0 ) {
out.write(buffer,0, len1);
}
out.close();
}
in.close();
Runtime.getRuntime().exec("chmod 755 "+getCacheDir() +"/"+ url);
videoView.setVideoPath("chmod 755 "+getCacheDir() +"/"+ url);
}else {
videoView.setVideoURI(Uri.parse(videoUrl));
}
} catch (Exception e) {
// TODO: handle exception
}
videoView.setVideoURI(Uri.parse(videoUrl));
MediaController mc = new MediaController(VideoViewC.this);
videoView.setMediaController(mc);
videoView.requestFocus();
videoView.start();
mc.show();
But I found Error java.net.SocketException: Connection reset by peer.
if you have any suggestion please give me.
I have my case problem, and it consisted in particular the my http server, which if not properly authenticate just closed the client connection, it is my Ask:
android-async-http Status code and response to onFailure
Maybe you have it too, due to the peculiarities of your httpservers
Did you implement caching video files?
I found this source code on the net and have modified it a little. But I get an error saying: java.io.FileNotFoundException /data/datafile.zip.
What should I do to get it running? Do I have to create the file first?
Thanks, Sigurd
private Thread checkUpdate = new Thread() {
public void run() {
try {
long startTime = System.currentTimeMillis();
Log.d("Zip Download", "Start download");
File file = new File(Environment.getDataDirectory(), "datafil.zip");
Log.d("Zip Download", file.getAbsolutePath());
URL updateURL = new URL("http://dummy.no/bilder/bilder/XML_Item_Expo_01.zip");
URLConnection conn = updateURL.openConnection();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
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(file);
fos.write(baf.toByteArray());
fos.close();
Log.d("Zip Download", "download ready in" + ((System.currentTimeMillis() - startTime) / 1000) + " sec");
} catch (Exception e) {
Log.d("Zip Download", "Error: " + e);
}
}
};
Seems like permission error. You maybe writing to the wrong place. Check that answer at link below,
Data directory has no read/write permission in Android
Environment.getDataDirectory() does not return a path where you can place files. You should use one of these methods instead:
Environment.getExternalStorageDirectory() gives you a path to external storage (SD card).
getFilesDir() from an Activity or other Context. Gives a path to app's internal file storage
You can also call openFileOutput() with a string file name (no path, just the file), which will open the FileOutputStream and create the file all in one shot for your use.
Hope that Helps!