In an android app, I am trying to download a file from a web server to /Download folder on external storage. download code is executed in a HandlerThread in a service. The service is doing other functions apart from downloading file. the code for downloading goes like this:
public void downloadFile(){
new Thread(new Runnable() {
#Override
public void run() {
try{
URL url = new URL("http://192.168.1.105/download/apkFile.apk");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
InputStream inputStream = connection.getInputStream();
File file = new File(Environment.getExternalStorageDirectory().getPath()+"/Download/apkFile.apk");
FileOutputStream fileOutputStream = new FileOutputStream(file);
int bytesRead;
byte[] buffer = new byte[4096];
while((bytesRead = inputStream.read(buffer)) != -1){
fileOutputStream.write( buffer, 0, bytesRead);
}
fileOutputStream.close();
inputStream.close();
}catch(Exception e){
e.printStackTrace();
}
}
}).start();
}
There is no error in executing but the file is not downloaded. Please suggest.
You can use AndroidDownloadManager.
This Class handles all the steps of the download of a file and gets you information about the progress ext...
You should avoid the use of threads.
This is how you use it:
public void StartNewDownload(url) {
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url)); /*init a request*/
request.setDescription("My description"); //this description apears inthe android notification
request.setTitle("My Title");//this description apears inthe android notification
request.setDestinationInExternalFilesDir(context,
"directory",
"fileName"); //set destination
//OR
request.setDestinationInExternalFilesDir(context, "PATH");
DownloadManager manager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
final long downloadId = manager.enqueue(request); //start the download and return the id of the download. this id can be used to get info about the file (the size, the download progress ...) you can also stop the download by using this id
}
call
connection.setDoInput(true);
connection.connect();
before
InputStream inputStream = connection.getInputStream();
Related
I have an app that downloads about 6k photos from a server and store them in a folder configured y my app settings, I keep the files hidden from the gallery with .nomedia file and they are only visible in my app gallery, but when I leave my device charging about 5000 photos disappears, and there are only about 920 left in the folder, I totally don't know why files are being deleted.
here is my download file code
DownloadManager downloadManager = (DownloadManager) activity.getSystemService(Context.DOWNLOAD_SERVICE);
DownloadManager.Request request;
fileURL = convertUri(fileURL);
if (!URLUtil.isValidUrl(fileURL)) { return false; }
Uri downloadUri = Uri.parse(fileURL);
String fileName = URLUtil.guessFileName(fileURL, null, MimeTypeMap.getFileExtensionFromUrl(fileURL));
deleteFileIfExists( new File( getAbsolutePath(path), fileName ));
request = new DownloadManager.Request(downloadUri);
request.setAllowedNetworkTypes( DownloadManager.Request.NETWORK_WIFI )
.setTitle(fileName)
.setAllowedOverRoaming(false)
.setVisibleInDownloadsUi(false)
.setDestinationInExternalPublicDir( getPath(path), fileName );
downloadManager.enqueue(request);
Add System.currenttimeMillisecond() to fileUrl to make sure that your file name not to be duplicate .
This weekend i tested with 3 different devices and 2 different download methods, in the one with download manager the files dissapeared, so if someone have the same problem here's how I am donwloading the files:
public static boolean downloadFile(Activity activity, String fileURL) {
fileURL = convertUri(fileURL);
if (!URLUtil.isValidUrl(fileURL)) { return false; }
try {
String fileName = URLUtil.guessFileName(fileURL, null, MimeTypeMap.getFileExtensionFromUrl(fileURL));
deleteFileIfExists( new File( activity.getExternalFilesDir(""), fileName ));
URL u = new URL(fileURL);
URLConnection conn = u.openConnection();
int contentLength = conn.getContentLength();
DataInputStream stream = new DataInputStream(u.openStream());
byte[] buffer = new byte[contentLength];
stream.readFully(buffer);
stream.close();
File file = new File(activity.getExternalFilesDir(""), fileName);
DataOutputStream fos = new DataOutputStream(new FileOutputStream(file));
fos.write(buffer);
fos.flush();
fos.close();
} catch(FileNotFoundException e) {
return false; // swallow a 404
} catch (IOException e) {
return false; // swallow a 404
}
return true;
}
I'm downloading a PDF from my server.
The server send me a HttpResponse with the InputStream of file's body.
I'm able to write it into a file but, when I try to read it with a PDF reader, it tells me that the file might be corrupted.
I've also noticed that the size of the PDF downloaded directly from web service is twice the size of the PDF downloaded via my application.
The code I use to download and write the PDF file is this:
String fileName = //FILENAME + ".pdf";
fileName = fileName.replaceAll("/", "_");
String extPath = Environment.getExternalStorageDirectory().toString();
String folderName = //FOLDERNAME;
try {
File folder = new File(extPath, folderName);
folder.mkdir();
File pdfFile = new File(folder, fileName);
pdfFile.createNewFile();
URL url = new URL(downloadURL);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
FileOutputStream fileOutputStream = new FileOutputStream(pdfFile);
byte[] buffer = new byte[MEGABYTE];
int bufferLength;
while((bufferLength = inputStream.read(buffer))>0 ){
fileOutputStream.write(buffer, 0, bufferLength);
}
fileOutputStream.close();
Uri path = Uri.fromFile(pdfFile);
Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
pdfIntent.setDataAndType(path, "application/pdf");
pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try {
startActivity(pdfIntent);
} catch (ActivityNotFoundException e) {
Toast.makeText(getApplicationContext(), "No Application available to view PDF", Toast.LENGTH_SHORT).show();
}
} catch (IOException e) {
e.printStackTrace();
}
//otherStuff
Where I go wrong?
I've also noticed that inside the Headers of HttpResponse contains Content-type:text/html. It shoudld be something like text/pdf?
Your Downloading code seems correct. Based on that and on your comment:
I've also noticed that the size of the PDF downloaded directly from web service is twice the size of the PDF downloaded via my application."
I would suggest checking your URL. It appears that you might be downloading an html page instead of the pdf. To verify you are downloading correctly, change the download directory as follows:
//Default download directory
String extPath = Environment.DIRECTORY_DOWNLOADS;
And check the directory (via the file system, e.g. mount the phone to your computer or a file manager app) for the downloaded content to verify it is a pdf.
I am trying to download a PPT file from a server.
it's in Bytes.
but while debugging I noticed that the input stream throws an exception of FileNotFound while running.. the file does exist on the server, here's my code, any help would be greatly appreciated.
public class DownloadFileAsync extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... aurl) {
int count;
try {
URL url = new URL(aurl[0]);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.addRequestProperty("Authorization", "Basic " + SharedPref.getAuthPrefValue());
connection.addRequestProperty("Device", BaseApplication.getCurrentDevice().getDevice().toString());
connection.addRequestProperty("DeviceId", BaseApplication.getCurrentDevice().getDeviceId());
connection.connect();
int lengthOfFile = connection.getContentLength();
Log.d("ANDRO_ASYNC", "Length of file: " + lengthOfFile);
InputStream input = new BufferedInputStream(url.openStream());
File sdcardDest = new File(Environment.getExternalStorageDirectory(), "Availo");
String finalDest = sdcardDest + File.separator + "Check1" + "." + "PPT";
OutputStream output = new FileOutputStream(finalDest);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress(""+(int)((total*100)/lengthOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
I am using Charles on Mac (which is similar to fiddler on windows.) to see what I send and receive from the server,
The server doesn't return any error, though it shows download steps for 6-7 sec, downloading around 400 bytes and then it stops.
The Exception is thrown from the input stream line.
Thanks!
I suggest you take a look at the DownloadManager system service. it's designed specifically for what you are trying to do:
(from the documentation)
The download manager is a system service that handles long-running
HTTP downloads. Clients may request that a URI be downloaded to a
particular destination file. The download manager will conduct the
download in the background, taking care of HTTP interactions and
retrying downloads after failures or across connectivity changes and
system reboots
While I do agree with Muzikant regarding the download manager,
FileNotFoundException is usually thrown when... the file is not found on the local device...
You need to do the following to make sure it doesnt happen
File dest = new File(finalDest);
try{
File parentDest = dest.getParentFile();
if(!parentDest.exists()){
parentDest.mkdirs(); //make all the directory structures needed
}
if(!dest.exists()){
dest.createNewFile();
}
OutputStream output = new FileOutputStream(dest);
//now you can use your file dest
//write data to it...
}catch (Exception e){
}
In my app I am using a webview to navigate through to a site, automatically fill in a web form using javascript then submit to obtain a link to a CSV export file.
The link looks like this: XYZ.com/TEST/index/getexport?id=130.
I'd like to download the file this URL points to, then when complete read it into a local database but I'm having trouble downloading the linked file.
If I simply try to open the URL in webview I get an error from the webpage telling me no such file exists.
If I use the Download Manager to download it myself, the source code is downloaded as an html file, not the associated .csv file.
I can open the url with an ACTION_VIEW intent and a browser (chrome) downloads the correct file, but this way I have no notification of when the download completes.
Any ideas of how to download my .CSV file?
To download a file from webview use this :
mWebView.setDownloadListener(new DownloadListener(){
public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength){
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
});
Hope this helps.
You could resort to manually downloading the file from the url using an AsyncTask.
Here id the background part:
#Override
protected String doInBackground(Void... params) {
String filename = "inputAFileName";
HttpURLConnection c;
try {
URL url = new URL("http://someurl/" + filename);
c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
} catch (IOException e1) {
return e1.getMessage();
}
File myFilesDir = new File(Environment
.getExternalStorageDirectory().getAbsolutePath()
+ "/Download");
File file = new File(myFilesDir, filename);
if (file.exists()) {
file.delete();
}
if ((myFilesDir.mkdirs() || myFilesDir.isDirectory())) {
try {
InputStream is = c.getInputStream();
FileOutputStream fos = new FileOutputStream(myFilesDir
+ "/" + filename);
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}
fos.close();
is.close();
} catch (Exception e) {
return e.getMessage();
}
if (file.exists()) {
return "File downloaded!";
} else {
Log.e(TAG, "file not found");
}
} else {
Log.e(TAG, "unable to create folder");
}
}
Perhaps it would make sense to refactor it so that the file is returned. Then you get the file as an argument in onPostExecute as soon as the download is complete.
I'm trying to share an image in an app I have made that downloads an Image and writes it to a file. But any time I try to share it, it says can't upload file or just does nothing. It's not coming up in the logcat so I'm kinda stuck for ideas on how to fix it.
The image that is downloaded is displayed in an image view like this
iView.setImageBitmap(im);
String path = ContentFromURL.Storage + "/temp.jpg";
File temp = new File(path);
uri = Uri.fromFile(temp);
iView.setImageURI(uri);
Asynch task to download file
HttpURLConnection connection;
try {
String url = params[0];
connection = (HttpURLConnection) new URL(url).openConnection();
connection.setRequestProperty("Accept-Charset","UTF-8");
connection.connect();
InputStream input = connection.getInputStream();
image = BitmapFactory.decodeStream(input);
File temp = new File(Storage,"temp.jpg");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
FileOutputStream fo = new FileOutputStream(temp);
fo.write(bytes.toByteArray());
fo.close();
String path = temp.getAbsolutePath();
Log.d("Asynch", "image shuould exist");
SharePage.act.runOnUiThread(new Runnable()
{
public void run()
{
SharePage.setImage(image);
}
}
);
creating intent
twitterIntent = new Intent(Intent.ACTION_SEND);
twitterIntent.setClassName("com.twitter.android",packageName);
twitterIntent.setType("image/jpeg");
twitterIntent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(twitterIntent);
I know that I should use the built in android share thing but its not working either when I try to share the image
The problem was where I was trying to store the Image, I wanted to have it so that the user never saw the image and it was deleted when it wasn't needed anymore but the other apps didn't have access to the directory. So I have since moved it to the external storage directory.