Uploading an image to a server in Android app - android

In my app I am capturing an image and uploading it to the server. The capturing and uploading part works fine in my Android device which is of 5 mega pixel.
But the app crashes occasionally when taking a photo. We've noticed if someone takes a
picture that has a high megapixel setting, the photo does not upload and the app crashes.
How to reduce the size of a 8 megapixel photo to be able to upload without crashing?
Do I have to compress the captured image. Following is my code to capture an image
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE,fileName);
mCapturedImageURI = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.ACTION_IMAGE_CAPTURE, capturedImage);
intent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
startActivityForResult(intent, 3);
I am uploading the image in OnActivity Result as follows
public void onActivityResult(int requestCode, int resultCode, final Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 3)
{
String[] projection = { MediaStore.Images.Media.DATA};
Cursor cursor = managedQuery(mCapturedImageURI, projection, null, null, null);
int column_index_data = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
capturedImage = cursor.getString(column_index_data);
String url = "http://xxxxxxxxxxxxxx.com/device_upload.php";
new ProfileAddImageFileAsync().execute(url);
}
}
And I am running a progress dialog box until the upload get completed, as follows
class ProfileAddImageFileAsync extends AsyncTask<String, String, String>
{
#Override
protected void onPreExecute()
{
super.onPreExecute();
showDialog(DIALOG_DOWNLOAD_PROGRESS);
}
protected String doInBackground(String... Aurl)
{
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
DataInputStream inStream = null;
try
{
URL urlServer = new URL(aurl[0]);
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
int maxBufferSize = 1*1024*1024;
FileInputStream fileInputStream = new FileInputStream(new File(capturedImage) );
connection = (HttpURLConnection) urlServer.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
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=\"userfile\";filename=\"" + capturedImage +"\"" + lineEnd);
outputStream.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
Log.e("bytesAvailable ",""+bytesAvailable);
bufferSize = Math.min(bytesAvailable, maxBufferSize);
Log.e("bufferSize ",""+bufferSize);
byte[] buffer = new byte[bufferSize];
Log.e("bufer ",""+buffer);
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);
#SuppressWarnings("unused")
int serverResponseCode = connection.getResponseCode();
#SuppressWarnings("unused")
String serverResponseMessage = connection.getResponseMessage();
fileInputStream.close();
outputStream.flush();
outputStream.close();
}
catch (Exception ex)
{
Log.e("SD Card image upload error: ","" + ex.getMessage());
}
try
{
inStream = new DataInputStream ( connection.getInputStream() );
String str;
while (( str = inStream.readLine()) != null)
{
IMAGE_RESPONSE = str;
ServerPost(str);
}
inStream.close();
}
catch (IOException ioex)
{
Log.e("SD card doFile upload error: ","" + ioex.getMessage());
}
return null;
}
protected void onProgressUpdate(String... Progress)
{
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
}
protected void onPostExecute(String unused)
{
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
}
}
Please help me friends, the above code is my working code in my 5MP camera.

i got solution like this, i use to capture and compress the image.
Following is my camera part
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
file = new File(Environment.getExternalStorageDirectory(), String.valueOf(System.currentTimeMillis()) + ".jpg");
Log.e("ffffffffffiiiiiiiiilllllllllle ",""+file);
f = String.valueOf(file);
mCapturedImageURI = Uri.fromFile(file);
Log.e("outputFileUri ",""+mCapturedImageURI);
setupImage(intent);
intent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
startActivityForResult(intent, 3);
i am uploading the image in OnActivity Result as follows
public void onActivityResult(int requestCode, int resultCode, final Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 3)
{
capturedImage = f;
String url = "http://xxxxxxxxxxxxxx.com/device_upload.php";
new ProfileAddImageFileAsync().execute(url);
}
}
And i am running an progress dialog box until the upload get completed, as follows
class ProfileAddImageFileAsync extends AsyncTask<String, String, String>
{
#Override
protected void onPreExecute()
{
super.onPreExecute();
showDialog(DIALOG_DOWNLOAD_PROGRESS);
}
protected String doInBackground(String... aurl)
{
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
DataInputStream inStream = null;
try
{
URL urlServer = new URL(aurl[0]);
Log.e("URl image uploading ",""+urlServer);
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
int maxBufferSize = 1*1024*1024;
Log.e("maxBufferSize ",""+maxBufferSize);
FileInputStream fileInputStream = new FileInputStream(new File(capturedImage) );
connection = (HttpURLConnection) urlServer.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
Log.e("FileInput Stream in image upload ",""+fileInputStream);
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=\"userfile\";filename=\"" + capturedImage +"\"" + lineEnd);
outputStream.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
Log.e("bytesAvailable ",""+bytesAvailable);
bufferSize = Math.min(bytesAvailable, maxBufferSize);
Log.e("bufferSize ",""+bufferSize);
byte[] buffer = new byte[bufferSize];
Log.e("bufer ",""+buffer);
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);
#SuppressWarnings("unused")
int serverResponseCode = connection.getResponseCode();
#SuppressWarnings("unused")
String serverResponseMessage = connection.getResponseMessage();
fileInputStream.close();
outputStream.flush();
outputStream.close();
}
catch (Exception ex)
{
Log.e("SD Card image upload error: ","" + ex.getMessage());
}
try
{
inStream = new DataInputStream ( connection.getInputStream() );
String str;
while (( str = inStream.readLine()) != null)
{
Log.e("ImageResponse ",""+str);
Appconstant.IMAGE_RESPONSE = str;
ProImgServerPost(str);
Log.e("ProImgServerPost ","added");
AddImgServerPost(str);
Log.e("AddImgServerPost ","added");
}
inStream.close();
}
catch (IOException ioex)
{
Log.e("SD card doFile upload error: ","" + ioex.getMessage());
}
return null;
}
protected void onProgressUpdate(String... progress)
{
Log.e("ANDRO_ASYNC",""+progress[0]);
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
// Bitmap bMap = BitmapFactory.decodeFile(capturedImage);
// ProfileImgPreview.setImageBitmap(bMap);
}
protected void onPostExecute(String unused)
{
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
Bitmap bMap = BitmapFactory.decodeFile(capturedImage);
ProfileImgPreview.setImageBitmap(bMap);
}
}

Related

How can I define an Array of Images and create a for loop for it to add into body of multipart data without LIBRARY?

I have tried to create an array of images looked for examples in treehouse and StackOverflow but many of them telling about creating an array of Int then defining images for the count of this int array.
My problems are first I need to create an array of images second I need to upload them to the server without the library. This array of images should be pass as a parameter to upload function. So that I can upload a single image and multiple images with the same function.
-Post Class
public class UploadImage {
public String multipartRequest(String urlTo, Map<String, String> parmas, File uploadFile, String filefield) {
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
InputStream inputStream = null;
String twoHyphens = "--";
String boundary = "*****" + Long.toString(System.currentTimeMillis()) + "*****";
String lineEnd = "\r\n";
String result = "";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
try {
String fileName = uploadFile.getName();
FileInputStream fileInputStream = new FileInputStream(uploadFile);
URL url = new URL(urlTo);
connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("User-Agent", "Android Multipart HTTP Client 1.0");
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=\"" + filefield + "\"; filename=\"" + fileName + "\"" + lineEnd);
outputStream.writeBytes("Content-Type: " + URLConnection.guessContentTypeFromName(fileName) + lineEnd);
outputStream.writeBytes("Content-Transfer-Encoding: binary" + 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);
// Upload POST Data
if (parmas != null){
Iterator<String> keys = parmas.keySet().iterator();
while (keys.hasNext()) {
String key = keys.next();
String value = parmas.get(key);
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"" + key + "\"" + lineEnd);
outputStream.writeBytes("Content-Type: text/plain" + lineEnd);
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(value);
outputStream.writeBytes(lineEnd);
}
}
outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
if (200 != connection.getResponseCode()) {
Log.i("firat", "Failed to upload code:" + connection.getResponseCode() + " " + connection.getResponseMessage());
}
inputStream = connection.getInputStream();
result = this.convertStreamToString(inputStream);
fileInputStream.close();
inputStream.close();
outputStream.flush();
outputStream.close();
return result;
} catch (Exception e) {
return "Error : " + e.toString();
}
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
-Usage
Map<String, String> params = new HashMap<String, String>(4);
params.put("name", "juan");
params.put("surname", "mata");
params.put("email", "matta#cimbom.com");
params.put("password", "1905");
UploadImage uploadImage = new UploadImage();
String result = uploadImage.multipartRequest("http://xxx:xx/xxx/addUser", params, file2, "file");
-OnActivityResult
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
if (requestCode == 1 && resultCode == RESULT_OK && null != data) {
Uri selectedImageUri = data.getData();
path2 = getPath(this.getApplicationContext(),selectedImageUri);
file2 = new File(path2);
// fileArray[k] = file2;
} // When an Video is picked
} catch (Exception e) {
Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG).show();
}
}
public static String getPath(Context context, Uri uri ) {
String result = null;
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = context.getContentResolver( ).query( uri, proj, null, null, null );
if(cursor != null){
if ( cursor.moveToFirst( ) ) {
int column_index = cursor.getColumnIndexOrThrow( proj[0] );
result = cursor.getString( column_index );
}
cursor.close( );
}
if(result == null) {
result = "Not found";
}
return result;
}

android- file not found onActivityResult for selecting files

I'm writing a code that allows my users to upload any kind of file , this is my code:
Intent fileIntent = new Intent(Intent.ACTION_GET_CONTENT);
fileIntent.setType("*/*"); // intent type to filter application based on your requirement
startActivityForResult(fileIntent, 1);
users are able to select their files and then I get the path and file name via this code :
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if (resultCode == Activity.RESULT_OK) {
String result = data.getStringExtra("result");
Uri u = data.getData();
filepath = u.getPath();
filename = u.toString();
chooseFile=true;
}
}
}
this is the my code for sending the selected file to server , I'm using assyctask . this is the code ;
#Override
protected String doInBackground(String... params) {
if (filepath != null) {//file entekhab shode bud
int serverResponseCode = 0;
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
DataInputStream inputStream = null;
String urlServer = getString(R.string.url)+"/getFile.php?id="+sefareshId;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
try {
FileInputStream fileInputStream = new FileInputStream(new File(filepath));
URL url = new URL(urlServer);
connection = (HttpURLConnection) url.openConnection();
// Allow Inputs & Outputs.
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
// Set HTTP method to POST.
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=\"" + filepath + "\"" + lineEnd);
outputStream.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// Read file
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);
serverResponseCode = connection.getResponseCode();
fileInputStream.close();
outputStream.flush();
outputStream.close();
} catch (Exception ex) {
Log.v("this", ex.getMessage());
}
return serverResponseCode + "";
} else
return "5";
}
by running this code ,I get this error:
/document/image:134342: open failed: ENOENT (No such file or directory)
I think the url path of this file is wrong , How can I get the correct path of file and then upload it ?
thanks

What's the issue with posting?

I have been using HttpUrlConnection to post a video and some other parameter,
the code runs fine else offcourse it does not post the data,it is able to get the
response from the server and i cant seem to figure out the issue.
Any help is appreciated ,Thankyou.
class MyAsyncTask extends AsyncTask<String, Void, String> {
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
DataInputStream inputStream = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
ProgressDialog dialog;
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
int serverResponseCode = 0;
String line = null;
String floatMessage = null;
#Override
protected void onPreExecute() {
dialog = new ProgressDialog(EventsActivity.this);
dialog.show();
dialog.setMessage("Uploading Event");
dialog.setCancelable(false);
super.onPreExecute();
}
#Override
protected String doInBackground(String... urls) {
try {
FileInputStream fileInputStream = new FileInputStream(new File(videopath));
URL url = new URL("http://workintelligent.com/TagFrame/webservice/upload_video");
connection = (HttpURLConnection) url.openConnection();
// Allow Inputs & Outputs.
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
// Set HTTP method to POST.
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
connection.setRequestProperty("video_file", videopath);
Log.e("getting user_id", userid);
connection.setRequestProperty("user_id",userid);
connection.setRequestProperty("access_type ", "public");
connection.setRequestProperty("title", "sdfdsf");
connection.setRequestProperty("description", "sdscfsdf");
connection.setRequestProperty("tags_keywords", "asdf");
connection.setRequestProperty("price", "0");
connection.setRequestProperty("is_paid", "0");
outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"video_file\";filename=\"" + videopath + "\"" + lineEnd);
outputStream.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// Read file
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);
connection.setRequestMethod("GET");
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
fileInputStream.close();
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line + '\n');
}
String jsonString = stringBuilder.toString();
Log.e("jsonString", jsonString);
JSONObject resJson = new JSONObject(jsonString);
String floatMessage = resJson.getString("upload");
Log.e("floatMessage", floatMessage);
outputStream.flush();
outputStream.close();
} catch (Exception ex) {
}
return floatMessage;
}
protected void onPostExecute(String result) {
dialog.cancel();
super.onPostExecute(result);
Toast.makeText(EventsActivity.this, floatMessage, Toast.LENGTH_LONG).show();
}
}

Android send image to webserver

I have this task to send a picture i take with my app to a webserver. this is my camera activity where i would like to send the image in the onActivityResult method. I have trouble finding up to date solutions to this as all i can find seems to be using MultipartEntity which is now deprecated.
package com.ndjk;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.widget.ImageView;
public class CameraActivity extends Activity {
private static final int CAMERA_REQUEST = 1888;
public ImageView imageView;
public static final String URI_PATH = "Uri";
Uri imageUri = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_frontpage);
imageView = (ImageView) findViewById(R.id.pictureImageView);
open();
}
public void open() {
Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
Bitmap bp = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(bp);
Intent frontPageIntent = new Intent(this, FrontPageActivity.class);
imageUri = data.getData();
frontPageIntent.putExtra(URI_PATH, imageUri.toString());
frontPageIntent.putExtra("MapPhoto", bp);
startActivity(frontPageIntent);
}
}
As an alternative, I would highly recommend using Retrofit a REST library from Square. Retrofit
You would create a Java interface like this:
#Multipart
#POST("/webservice/{userid}/avatar.json")
Object uploadImage(
#Header("Rest-User-Token") String token,
#Path("userid") String userId,
#Part("FileData") TypedFile pictureFile
);
Then it is just a case of converting the Intent data to a File object, and than creating a TypedFile as follows:
TypedFile in = new TypedFile("image/jpeg", imageFile);
I think the answer is here:
https://stackoverflow.com/a/19196621/1652236
You should use MultipartEntityBuilder as an alternative
Edit - 1
You can open camera with this code:
private static final int RESULT_TAKE_PHOTO = 1;
Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(i, RESULT_TAKE_PHOTO);
Your onActivityResult must be like this :
if (resultCode == RESULT_OK) {
File file = null;
String filePath = null;
try {
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
filePath = cursor.getString(columnIndex);
cursor.close();
rotateDegree = getCameraPhotoOrientation(getApplicationContext(), selectedImage, picturePath);
bmp = BitmapFactory.decodeFile(picturePath);
bmp = rotateImage(bmp, rotateDegree);
file = new File(filePath);
FileOutputStream fOut = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.JPEG, 70, fOut);
fOut.flush();
fOut.close();
resultCode=0;
} catch (Exception e) {
e.printStackTrace();
}
}
So if take the picture You can use this AsyncTask for sending. You can show a progress bar while sending file to server. It's working for me.
public class SendFile extends AsyncTask<String, Integer, Integer> {
private Context conT;
private ProgressDialog dialog;
private String SendUrl = "";
private String SendFile = "";
private String Parameters = "";
private String result;
public File file;
SendFile(Context activity, String url, String filePath, String values) {
conT = activity;
dialog = new ProgressDialog(conT);
SendUrl = url;
SendFile = filePath;
Parameters = Values;
}
#Override
protected void onPreExecute() {
file = new File(SendFile);
dialog.setMessage("Please Wait..");
dialog.setCancelable(false);
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.setMax((int) file.length());
dialog.show();
}
#Override
protected Integer doInBackground(String... params) {
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
InputStream inputStream = null;
String twoHyphens = "--";
String boundary = "*****"
+ Long.toString(System.currentTimeMillis()) + "*****";
String lineEnd = "\r\n";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 512;
String[] q = SendFile.split("/");
int idx = q.length - 1;
try {
FileInputStream fileInputStream = new FileInputStream(file);
URL url = new URL(SendUrl);
connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("User-Agent",
"Android Multipart HTTP Client 1.0");
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=dosya; filename=\""
+ q[idx] + "\"" + lineEnd);
outputStream.writeBytes("Content-Type: image/jpg" + lineEnd);
outputStream.writeBytes("Content-Transfer-Encoding: binary"
+ lineEnd);
outputStream.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
int boyut = 0;
while (bytesRead > 0) {
boyut += bytesRead;
outputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
dialog.setProgress(boyut);
}
outputStream.writeBytes(lineEnd);
String[] posts = Bilgiler.split("&");
int max = posts.length;
for (int i = 0; i < max; i++) {
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
String[] kv = posts[i].split("=");
outputStream
.writeBytes("Content-Disposition: form-data; name=\""
+ kv[0] + "\"" + lineEnd);
outputStream.writeBytes("Content-Type: text/plain"
+ lineEnd);
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(kv[1]);
outputStream.writeBytes(lineEnd);
}
outputStream.writeBytes(twoHyphens + boundary + twoHyphens
+ lineEnd);
inputStream = connection.getInputStream();
result = this.convertStreamToString(inputStream);
Log.v("TAG","result:"+result);
fileInputStream.close();
inputStream.close();
outputStream.flush();
outputStream.close();
} catch (Exception e) {
}
return null;
}
#Override
protected void onProgressUpdate(Integer... progress) {
dialog.setProgress(progress[0]);
}
#Override
protected void onPostExecute(Integer result1) {
dialog.dismiss();
};
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(
new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
and if you are sending to PHP server, this code will help you.
<?php
$file_path = "test/";
$username= $_POST["username"];
$password= $_POST["password"];
$file_path = $file_path . basename( $_FILES['uploaded_file']['name']);
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $file_path)) {
echo "success";
} else{
echo "fail";
}
?>
Edit - 2:
you can call this AsyncTask like :
String FormData = "username=" + Session.getUsername()
+ "&password=" + Session.getPassword() ;
SendFile SendIt= new SendFile(this, upLoadServerUri, filePath,FormData);
SendIt.execute();

how to capture images and post using json in android

I have two url, one for post captured image name and second for store image on that location. Now i finished process of open camera. When i take photo then image is stored on DCIM/CAMARA on device phone memory directory. But image is not post and store on two different url. What can i do for that?
Code for Open Camara
btn_camera = (Button)findViewById(R.id.btn_camera);
btn_camera.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
startActivityForResult(intent, RESULT_LOAD_IMAGE);
// post(Image_URL, null);
}
});
> Code for Post data on url
try{
ArrayList<NameValuePair> mNameValuePair = new ArrayList<NameValuePair>();
mNameValuePair.add(new BasicNameValuePair("lid", lotids));
mNameValuePair.add(new BasicNameValuePair("aid", attandant_id));
mNameValuePair.add(new BasicNameValuePair("vnum", vehicle_number));
mNameValuePair.add(new BasicNameValuePair("imag", "xyz"));
Log.i("NameValuePair","" + mNameValuePair);
result = mCommonClass.PostConnection(Issue_Summons_Url, mNameValuePair);
Log.i("result for log",""+ result);
}
catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
Log.e("FastPark App","Nothing to be display");
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
// get image from camera
case REQUEST_CODE_CAMERA_IMAGE:
if (resultCode == Activity.RESULT_OK) {
// Uri cameraImageUri = data.getData();
Log.e("", "camera uri= " + Uri.fromFile(getFile()));
String path=getFile().getAbsolutePath();
prepareTouploadImage(path);
}
break;
default;
break;
}
use this...in your main activity...u can get path from image
you can find the uri of the file from the camera intent and convert it to a binary data and upload it to the web service
How to upload a image to server using HttpPost in android? ,or if you want to store it in a different location other than in DCIM/CAMERA you can refer this webpage http://developer.android.com/training/camera/photobasics.html
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
// get image from camera
case REQUEST_CODE_CAMERA_IMAGE:
if (resultCode == Activity.RESULT_OK) {
// Uri cameraImageUri = data.getData();
Log.e("", "camera uri= " + Uri.fromFile(getFile()));
String path=getFile().getAbsolutePath();
prepareTouploadImage(path);
}
break;
default;
break;
this path return your camera image path..
and this path will be posted in json.
/**
* encodes image to string using Base64
*
* #return
*/
private String prepareTouploadImage(String profileImagePath) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap = BitmapFactory.decodeFile(profileImagePath, options);
bitmap=Bitmap.createScaledBitmap(bitmap, 50, 50, true);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 50, baos);
bitmap.compress(Bitmap.CompressFormat.JPEG, 50, baos);
byte[] byteArray = baos.toByteArray();
String imageString = com.eg_lifestyle.utils.Base64
.encodeBytes(byteArray);
bitmap = null;
System.gc();
Runtime.getRuntime().gc();
return imageString;
}
this above method returns image converted to binary and return string
private void doFileUpload(){
HttpURLConnection conn = null;
DataOutputStream dos = null;
DataInputStream inStream = null;
String exsistingFileName = "/sdcard/six.3gp";
// Is this the place are you doing something wrong.
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;
String urlString = "http://192.168.1.5/upload.php";
try
{
Log.e("MediaPlayer","Inside second Method");
FileInputStream fileInputStream = new FileInputStream(new File(exsistingFileName) );
URL url = new URL(urlString);
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
// Allow Outputs
conn.setDoOutput(true);
// Don't use a cached copy.
conn.setUseCaches(false);
// Use a post method.
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
dos = new DataOutputStream( conn.getOutputStream() );
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + exsistingFileName +"\"" + lineEnd);
dos.writeBytes(lineEnd);
Log.e("MediaPlayer","Headers are written");
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
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);
}
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
tv.append(inputLine);
// close streams
Log.e("MediaPlayer","File is written");
fileInputStream.close();
dos.flush();
dos.close();
}
catch (MalformedURLException ex)
{
Log.e("MediaPlayer", "error: " + ex.getMessage(), ex);
}
catch (IOException ioe)
{
Log.e("MediaPlayer", "error: " + ioe.getMessage(), ioe);
}
//------------------ read the SERVER RESPONSE
try {
inStream = new DataInputStream ( conn.getInputStream() );
String str;
while (( str = inStream.readLine()) != null)
{
Log.e("MediaPlayer","Server Response"+str);
}
/*while((str = inStream.readLine()) !=null ){
}*/
inStream.close();
}
catch (IOException ioex){
Log.e("MediaPlayer", "error: " + ioex.getMessage(), ioex);
}
use this function....i hope its useful to you to store images in specific folder on server

Categories

Resources