I face a problem during downlonading an image in Android.
The problematic image link:
https://via.placeholder.com/150/92c952
I can use postman to download the image successfully (200).
But when I code in Android, using HttpConnection, it responds me with error status code 410.
(And then triggers FileNotFounedException.)
Below is my code,
URL url = new URL(fileURL);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
int 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());
}
System.out.println("Content-Type = " + contentType);
System.out.println("Content-Disposition = " + disposition);
System.out.println("Content-Length = " + contentLength);
System.out.println("fileName = " + fileName);
// opens input stream from the HTTP connection
InputStream inputStream = httpConn.getInputStream();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
int bytesRead = -1;
byte[] buffer = new byte[1024];
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
inputStream.close();
System.out.println("File downloaded");
httpConn.disconnect();
return outputStream.toByteArray();
} else {
httpConn.disconnect();
throw new RuntimeException("Error code: " + responseCode);
}
My code can successfully download images from Imgur, but as for this link, it fails.
Please share any idea, I do appreciated a lot!
It's quite a simple reason.
The cause is not at your Java program side but at the server side.
The server rejects your connection by responding HTTP 410 Gone.
To dodge the server's behavior, just set any popular User-Agent string on your request before doing actual request.
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
httpCon.setRequestProperty(
"User-Agent",
"Mozilla/5.0 (Macintosh; U; Intel Mac OS X; ja-JP-mac; rv:1.8.1.6) Gecko/20070725 Firefox/2.0.0.6"
);
int responseCode = httpConn.getResponseCode();
...
if you wanna download image and show it on ImageView you can use glide or picasso. its pretty easy to implement, on glide you can just
Glide.with(context).load("https://via.placeholder.com/150/92c952").into(myImageView);
Use this method to download image from URL
// DownloadImage AsyncTask
private class DownloadImage extends AsyncTask<String, Void, Bitmap> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Bitmap doInBackground(String... URL) {
String imageURL = URL[0];
Bitmap bitmap = null;
try {
// Download Image from URL
InputStream input = new java.net.URL(imageURL).openStream();
// Decode Bitmap
bitmap = BitmapFactory.decodeStream(input);
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
#Override
protected void onPostExecute(Bitmap result) {
// set this bitmap to image view
// NOW USE THIS BITMAP TO SAVE IMAGE IN MEMORY, I SAVED IN INTERNAL MEMORY
if (result != null) {
File destination = new File(getActivity().getCacheDir(),
"profile" + ".jpg");
try {
destination.createNewFile();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
result.compress(Bitmap.CompressFormat.PNG, 0 /*ignored for PNG*/, bos);
byte[] bitmapdata = bos.toByteArray();
FileOutputStream fos = new FileOutputStream(destination);
fos.write(bitmapdata);
fos.flush();
fos.close();
selectedFile = destination;
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Now call this method like this
new DownloadImage().execute("https://via.placeholder.com/150/92c952");
Related
Here I am trying to download a image from server. But it is always throwing Exception. Can any One tell me Why it is Happening and what will be the Correct way?
public static String getBitmap(String url) throws IOException {
InputStream is = (InputStream) new URL(url).getContent();
Bitmap bmp= BitmapFactory.decodeStream(is);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] b=stream.toByteArray();
String encoded = Base64.encodeToString(b, Base64.DEFAULT);
is.close();
return encoded;
}
Please try this functions get bitmap and download the bitmap
Bitmap bitmap = getBitmapfromUrl(imageurl);
imageview.setImageBitmap(bitmap);
SaveImage(bitmap);
public Bitmap getBitmapfromUrl(String imageUrl) {
try {
URL url = new URL(imageUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(input);
return bitmap;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
private void SaveImage(Bitmap finalBitmap) {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/saved_images");
myDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Image-" + n;
File file = new File(myDir, fname);
if (file.exists()) file.delete();
try {
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
And Add this permision in your manifest file
Call this function from your activity and get inputStream. After getting inputStream (Bitmap bitmap = Bitmap.decodeStream(inputStream));
private InputStream OpenHttpConnection(String urlString) throws IOException
{
InputStream in = null;
int response = -1;
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
if (!(conn instanceof HttpURLConnection)) throw new IOException("Not an HTTP connection");
try{
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
response = httpConn.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
}
}
catch (Exception ex)
{
throw new IOException("Error connecting");
}
return in;
}
Try using Glide or Picasso image processing library.
here is Glide demo
Glide.with(this).load(YourImageURL)
.diskCacheStrategy(DiskCacheStrategy.SOURCE)
.into(Imageview);
and add this dependency in gradle.
compile 'com.github.bumptech.glide:glide:3.7.0'
you can also set placeholder while image loading. its like alt attribute in html
Glide.with(this).load(YourImageURL)
.diskCacheStrategy(DiskCacheStrategy.SOURCE)
.placeholder(R.drawable.backimage)
.into(Imageview);
Here is Picasso demo
Picasso.with(context).load(url).placeholder(R.drawable.user_placeholder)
.error(R.drawable.user_placeholder_error)
.into(imageView);
and add this dependency:
compile 'com.squareup.picasso:picasso:2.5.2'
these lib also provide cache feature so you don't need to load second time.
I want to download files from Zippyshare site in Android.
The problem is that content length returned is -1. So I am not able to download a valid file.
Here is my code
public class DownloadFileDemo1 extends Activity {
ProgressBar pb;
Dialog dialog;
int downloadedSize = 0;
int totalSize = 0;
TextView cur_val;
String dwnload_file_path = "http://www17.zippyshare.com/i/95748527/55444/image.jpeg";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
showProgress(dwnload_file_path);
new Thread(new Runnable() {
public void run() {
downloadFile();
}
}).start();
}
void downloadFile(){
try {
URL url = new URL(dwnload_file_path);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestProperty("Accept-Encoding", "gzip");
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,"downloaded_file.png");
FileOutputStream fileOutput = new FileOutputStream(file);
//Stream used for reading the data from the internet
InputStream inputStream = urlConnection.getInputStream();
System.out.println("ENCODING"+urlConnection.getContentEncoding());
if ("gzip".equals(urlConnection.getContentEncoding())) {
inputStream = new GZIPInputStream(inputStream);
}
InputSource is = new InputSource(inputStream);
//this is the total size of the file which we are downloading
totalSize = urlConnection.getContentLength();
runOnUiThread(new Runnable() {
public void run() {
pb.setMax(totalSize);
}
});
//create a buffer...
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
fileOutput.write(buffer, 0, bufferLength);
downloadedSize += bufferLength;
// update the progressbar //
runOnUiThread(new Runnable() {
public void run() {
pb.setProgress(downloadedSize);
float per = ((float)downloadedSize/totalSize) * 100;
cur_val.setText("Downloaded " + downloadedSize + "KB / " + totalSize + "KB (" + (int)per + "%)" );
}
});
}
//close the output stream when complete //
fileOutput.close();
runOnUiThread(new Runnable() {
public void run() {
// pb.dismiss(); // if you want close it..
}
});
} catch (final MalformedURLException e) {
showError("Error : MalformedURLException " + e);
e.printStackTrace();
} catch (final IOException e) {
showError("Error : IOException " + e);
e.printStackTrace();
}
catch (final Exception e) {
showError("Error : Please check your internet connection " + e);
}
}
void showError(final String err){
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(DownloadFileDemo1.this, err, Toast.LENGTH_LONG).show();
}
});
}
void showProgress(String file_path){
dialog = new Dialog(DownloadFileDemo1.this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.myprogressdialog);
dialog.setTitle("Download Progress");
TextView text = (TextView) dialog.findViewById(R.id.tv1);
text.setText("Downloading file from ... " + file_path);
cur_val = (TextView) dialog.findViewById(R.id.cur_pg_tv);
cur_val.setText("Starting download...");
dialog.show();
pb = (ProgressBar)dialog.findViewById(R.id.progress_bar);
pb.setProgress(0);
pb.setProgressDrawable(getResources().getDrawable(R.drawable.green_progress));
}
}
How can I solve this problem?
According to documentation of getContentLength:
Returns the content length in bytes specified by the response header
field content-length or -1 if this field is not set or cannot be
represented as an int.
If you will check your link here, then you will spot, that Content Length was not set.
(I will just add, that I was not checking fully your code, but generally in main downloading loop with buffer - is downloading something, but I was not checking if it was correct, or not)
EDIT: I'm gonna 'hate' guy, that gave me '-1'. I'm helping with detail link and how checking it, why content length is returning -1, and someone is giving me negative. I change little downloadFile function just to download file, without giving update to UI, and then we have:
void downloadFile(){
try {
URL url = new URL(dwnload_file_path);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestProperty("Accept-Encoding", "gzip");
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
//connect
urlConnection.connect();
//set the path where we want to save the file
//create a new file, to save the downloaded file
File file = new File("downloaded_file.png");
FileOutputStream fileOutput = new FileOutputStream(file);
//Stream used for reading the data from the internet
InputStream inputStream = urlConnection.getInputStream();
System.out.println("ENCODING"+urlConnection.getContentEncoding());
if ("gzip".equals(urlConnection.getContentEncoding())) {
inputStream = new GZIPInputStream(inputStream);
}
InputSource is = new InputSource(inputStream);
//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;
// update the progressbar //
}
//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();
}
}
As I checked this code is downloading file, but it isn't this image, but html page from zippyshare, as zippy has kind of protection to download files from their site.
I'm trying to design an application that starts a camera intent, uploads a photo, (and hopefully, work in progress: parse an XML response from the server, then move to another activity and fill in some form fields).
The problem is that so far the upload code is executed the 1st time I run the application, the 2nd time it gets skipped, the 3rd time works fine, 4th skips and so on.
MainActivity:
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// buttons
Button lunchCamBtn = (Button) findViewById(R.id.lunchVerBtn);
lunchCamBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
}
});
Button lunchCaptBtn = (Button) findViewById(R.id.lunchCaptBtn);
lunchCaptBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
dispatchTakePictureIntent();
}
});
}
String path;
String picfname;
static final int REQUEST_IMAGE_CAPTURE = 1;
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
File dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
Random rnd = new Random(System.currentTimeMillis());
DateFormat dateFormat = new SimpleDateFormat("ddMMyyyy");
Date date = new Date();
String picfname = "bul "+dateFormat.format(date)+" "+rnd.nextInt(90)+".png";
File output = new File(dir,picfname);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(output));
path = output.getAbsolutePath();
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Toast.makeText(getApplicationContext(), path.toString(),
Toast.LENGTH_LONG).show();
UploadFiles upld =new UploadFiles(MainActivity.this);
upld.execute(path.toString());
}
UploadFiles:
public class UploadFiles extends AsyncTask<String, Integer, Boolean> {
WeakReference<Activity> mActivityReference;
public UploadFiles(Activity activity){
this.mActivityReference = new WeakReference<Activity>(activity);
}
#Override
protected Boolean doInBackground(String... params) {
Boolean succesz = true;
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
DataInputStream inputStream = null;
String selectedPath = params[0];
String pathToOurFile = selectedPath;
String urlServer = "http://192.168.0.104/upload2.php";
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
try {
Bitmap bmp = BitmapFactory.decodeFile(pathToOurFile);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 90, bos);
InputStream fileInputStream = new ByteArrayInputStream(bos.toByteArray());
URL url = new URL(urlServer);
connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setChunkedStreamingMode(1024);
connection.setReadTimeout(25000 /* milliseconds */);
connection.setConnectTimeout(30000 /* milliseconds */);
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream
.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\""
+ pathToOurFile + "\"" + lineEnd);
outputStream.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
outputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(twoHyphens + boundary + twoHyphens
+ lineEnd);
InputStream stream = connection.getInputStream();
InputStreamReader isReader = new InputStreamReader(stream);
String line = "";
line = convertStreamToString(stream);
System.out.print(line);
fileInputStream.close();
outputStream.flush();
outputStream.close();
} catch (Exception ex) {
}
return succesz;
}
private String convertStreamToString(InputStream is) {
String line = "";
StringBuilder total = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((line = rd.readLine()) != null) {
total.append(line);
}
} catch (Exception e) {
//Toast.makeText(this, "Stream Exception", Toast.LENGTH_SHORT).show();
}
return total.toString();
}
#Override
protected void onPostExecute(Boolean result) {
if (result && mActivityReference.get() != null) {
Activity activity = mActivityReference.get();
Intent iinent= new Intent(activity,TestActivity.class);
activity.startActivity(iinent);
//activity.finish();
}
}}
I know now that this issue is caused by the convertStreamToString method in class UploadFiles but I can't understand what exactly causes it. When I remove it completely everything works fine. Thank you in advance!
The first minor problem:
Using available is basically wrong, though it might work.
The second minor problem:
Do not use DataOutputStream here. I guess it is done to be able to write Strings to an OutputStream.
response.setContentType("...; charset=Windows-1252");
BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(os, "Windows-1252"));
Somehow also specifying the encoding/charset may help.
Problem with the convertStreamToString:
In no extra encoding parameter is added to the InputStreamReader, the default platform encoding is used. UTF-8 on Android. That would fail relatively fast.
You might give a less strict single-byte encoding a try to see what happens:
BufferedReader rd = new BufferedReader(new InputStreamReader(is, "Windows-1252"));
In general encoding is not handled: URLConnection.getContentEncoding() maybe is informative.
You are doing couple of things wrong here.
Don't leave exception blocks empty. It hides all the error. Use Log.e to print that.
Don't use System.out.println. Use Log.* only for logging.
Don't use AsyncTask to upload your file. Use IntentService Instead. And using localbroadcastmanager broadcast upload events for your activity to listen. It will be more configuration change friendly.
Instead of doing all this file upload sorcery yourself. Use httpmime library instead. It works simply awesome on android. I have my apps on production using this. Something like this you have to do.
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(urlToUpload);
MultipartEntity entity = new MultipartEntity();
Bitmap bmp = BitmapFactory.decodeFile(sourceFileUri);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bmp.compress(CompressFormat.JPEG, 50, bos);
InputStream in = new ByteArrayInputStream(bos.toByteArray());
ContentBody imageContent = new InputStreamBody(in, "image/jpeg", sourceFile.getName());
entity.addPart("file", imageContent);
post.setEntity(entity);
HttpResponse response = client.execute(post);
You will have your everything in 'response' for you to read.
String responseBody = EntityUtils.toString(response.getEntity());
From here you can download this library http://repo1.maven.org/maven2/org/apache/httpcomponents/httpmime/4.2.5/
I have used this https://github.com/alexbbb/android-upload-service for file uploads.
I handle all the response-related logic inside the Broadcast receiver, where I'm waiting for the upload responses.
I am having trouble figuring out how to pass the image's uri as I need it to grab the file unless there is another way and I just don't see it (I am pretty new to this). I have the image selected working and setting the imageview's bitmap to the bitmap but now trying to have it be send to the server once the submit button is clicked.
I know I can do execute(uri); but how do I actually pull out the uri from the imageview?
Here is the code : )
public class wardrobe extends Activity implements OnClickListener {
// set variable for the fields
private EditText nameField, sizeField, colorField, quantityField;
private Spinner typeField, seasonField;
private ImageView imageview;
private ProgressBar progressBarField;
private TextView imageTextSelect, resImage;
private ProgressDialog progressDialog = null;
private int serverResponseCode = 0;
private Button uploadImageButton, postWardrobe;
private String upLoadServerUri = null;
private String imagepath = null;
private Bitmap bitmap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.wardrobe);
// image upload stuff
imageview = (ImageView) findViewById(R.id.user_photo);
imageTextSelect = (TextView) findViewById(R.id.imageTextSelect);
// button for upload image
uploadImageButton = (Button) findViewById(R.id.uploadImageButton);
// button for posting details
postWardrobe = (Button) findViewById(R.id.postButton);
uploadImageButton.setOnClickListener(this);
postWardrobe.setOnClickListener(this);
#Override
public void onClick(View v) {
/**
* Opens dialog picker, so the user can select image from the gallery.
* The result is returned in the method <code>onActivityResult()</code>
*/
if (v == uploadImageButton) {
// below allows you to open the phones gallery
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(
Intent.createChooser(intent, "Complete action using"), 1);
}
if (v == postWardrobe) {
// execute the post request
new ImageUploadTask().execute();
}
}
}
/**
* Retrives the result returned from selecting image, by invoking the method
* <code>selectImageFromGallery()</code>
*/
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK && requestCode == 1 && null != data) {
decodeUri(data.getData());
}
}
public void decodeUri(Uri uri) {
ParcelFileDescriptor parcelFD = null;
try {
parcelFD = getContentResolver().openFileDescriptor(uri, "r");
FileDescriptor imageSource = parcelFD.getFileDescriptor();
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFileDescriptor(imageSource, null, o);
// the new size we want to scale to
final int REQUIRED_SIZE = 1024;
// Find the correct scale value. It should be the power of 2.
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE) {
break;
}
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
bitmap = BitmapFactory.decodeFileDescriptor(imageSource, null, o2);
imageview.setImageBitmap(bitmap);
// can take off below just shows path
imageTextSelect.setText("select : " + uri);
} catch (FileNotFoundException e) {
// handle errors
} catch (IOException e) {
// handle errors
} finally {
if (parcelFD != null)
try {
parcelFD.close();
} catch (IOException e) {
// ignored
}
}
}
PART I AM TRYING TO GET WORKING : )
private class ImageUploadTask extends AsyncTask<Void, Void, String> {
What I need is the uri or the file...
String fileName = imagepath;
File sourceFile = new File(imagepath);
private String webAddressToPost = "http://10.0.2.2/wardrobe";
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
// private ProgressDialog dialog
private ProgressDialog progressDialog = new ProgressDialog(
wardrobe.this);
#Override
protected void onPreExecute() {
progressDialog.setMessage("Uploading...");
progressDialog.show();
}
#Override
protected String doInBackground(Void... arg0) {
if (!sourceFile.isFile()) {
progressDialog.dismiss();
Log.e("uploadFile", "Source File not exist :" + imagepath);
runOnUiThread(new Runnable() {
public void run() {
imageTextSelect.setText("Source File not exist :"
+ imagepath);
}
});
return 0;
} else {
try {
// open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(
sourceFile);
URL url = new URL(upLoadServerUri);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true); // Allow Inputs
conn.setDoOutput(true); // Allow Outputs
conn.setUseCaches(false); // Don't use a Cached Copy
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("uploaded_file", fileName);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
+ fileName + "\"" + lineEnd);
dos.writeBytes(lineEnd);
// create a buffer of maximum size
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// Responses from the server (code and message)
serverResponseCode = conn.getResponseCode();
String serverResponseMessage = conn.getResponseMessage();
Log.i("uploadFile", "HTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode);
if (serverResponseCode == 200) {
String msg = "File Upload Completed.\n\n See uploaded file here : \n\n"
+ " F:/wamp/wamp/www/uploads";
imageTextSelect.setText(msg);
Toast.makeText(wardrobe.this,
"File Upload Complete.", Toast.LENGTH_SHORT)
.show();
}
// close the streams //
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
progressDialog.dismiss();
ex.printStackTrace();
imageTextSelect
.setText("MalformedURLException Exception : check script url.");
Toast.makeText(wardrobe.this, "MalformedURLException",
Toast.LENGTH_SHORT).show();
Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
} catch (Exception e) {
progressDialog.dismiss();
e.printStackTrace();
imageTextSelect.setText("Got Exception : see logcat ");
Toast.makeText(wardrobe.this,
"Got Exception : see logcat ",
Toast.LENGTH_SHORT).show();
Log.e("Upload file to server Exception",
"Exception : " + e.getMessage(), e);
}
}
You have to use http post with multipart data to upload images.
try this link
I want to download and save pdf file to internal storage. Here is code that i am using:
I am calling my method from other class:
new Thread(new Runnable() {
public void run() {
new Main().downloadPdfContent("http://people.opera.com/howcome/2005/ala/sample.pdf");
}
}).start();
Method look like this:
public void downloadPdfContent(String urlToDownload){
URLConnection urlConnection = null;
try{
URL url = new URL(urlToDownload);
//Opening connection of currrent url
urlConnection = url.openConnection();
urlConnection.connect();
//int lenghtOfFile = urlConnection.getContentLength();
String PATH = Environment.getExternalStorageDirectory() + "/1/";
File file = new File(PATH);
file.mkdirs();
File outputFile = new File(file, "test.pdf");
FileOutputStream fos = new FileOutputStream(outputFile);
InputStream is = url.openStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}
fos.close();
is.close();
System.out.println("--pdf downloaded--ok--"+urlToDownload);
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
I found link of pdf on the web:
http://people.opera.com/howcome/2005/ala/sample.pdf
However i get an exception on this line:
urlConnection.connect();
Exception:
java.net.UnknownHostException: people.opera.com
I can't figure out what's wrong. Maybe someone could take a look.
Thanks.
Put
<uses-permission android:name="android.permission.INTERNET"/>
in your AndroidManifest.xml
Follow following steps :
1) Declare file name
String fileName;
//for image
fileName = "matchfine1.png";
//for pdf
fileName = "samplepdf.pdf";
2) Call method to invoke download process.
startDownload(fileName);
3) Define startDownload method:
//for download file start
private void startDownload(String filename) {
String filedowname = filename;
//for image
String url = "http://farm1.static.flickr.com/114/298125983_0e4bf66782_b.jpg";
//for pdf
String url = "http://people.opera.com/howcome/2005/ala/sample.pdf";
new DownloadFileAsync().execute(url,filedowname);
}
4) For auto loading progressBar:
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_DOWNLOAD_PROGRESS:
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage("Downloading file..");
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
return mProgressDialog;
default:
return null;
}
}
5) Define the download process extending AsyncTask
class DownloadFileAsync extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(DIALOG_DOWNLOAD_PROGRESS);
}
#Override
protected String doInBackground(final String... aurl) {
try {
File root = android.os.Environment.getExternalStorageDirectory();
File dir = new File (root.getAbsolutePath() + "/Your_file_save_path/");
if(dir.exists()==false) {
dir.mkdirs();
}
URL url = new URL(aurl[0]);
String filename = aurl[1];
URLConnection conexion = url.openConnection();
conexion.connect();
int lenghtOfFile = conexion.getContentLength();
Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(dir+"/"+filename);
byte data[] = new byte[1024];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress(""+(int)((total*100)/lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {}
return null;
}
protected void onProgressUpdate(String... progress) {
Log.d("ANDRO_ASYNC", progress[0]);
mProgressDialog.setProgress(Integer.parseInt(progress[0]));
}
#Override
protected void onPostExecute(String unused) {
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
}
}
//for download file end
6) Replace "Your_file_save_path" by your file path in dir. and then download and check in the specified location.
I have used the same code and got Network.onThreadException Error. But then after using this piece of code in my oncreate() method, I was able to resolve the issue.
if (android.os.Build.VERSION.SDK_INT > 9)
{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}