Android send image to webserver - android

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();

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;
}

How to upload Less than 1 MB image in Android Using volley library?

I want to check less than 1 MB image and upload to remote server using volley library in Android.....please help me.
For select image I use this code:
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"),PICK_IMAGE_REQUEST);
In Activity Result I Use:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
try {
if (Build.VERSION.SDK_INT>19){
}else {
Uri filePath = data.getData();
File file = new File(filePath.getPath());
int length = (int) file.length();
double lengthkb = length / 1024;
if (lengthkb > 0.0D) {
lengthmb = lengthkb / 1024;
Log.d("picsize", lengthmb + "");
} else {
File file2 = new File(getPath(filePath));
int length2 = (int) file2.length();
double lengthkb2 = length2 / 1024;
lengthmb = lengthkb2 / 1024;
Log.d("picsize", lengthmb + "");
}
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath); imageViewProfileImage.setImageBitmap(bitmap); }
} catch(IOException e){
e.printStackTrace();
}
}
}
After You pick image from gallery the bellow code in that code you pass parameters and image URL.
Upload Image Method :
private void uploadPatientReport() {
dialog = ProgressDialog.show(getContext(), "", "Uploading file...", true);
final Map<String, String> parameters = new HashMap<String, String>();
parameters.put(Constant.ACTION, "reports");
parameters.put(Constant.ROLE_ID, SafeUtils.getRoleID(getContext()));
parameters.put(Constant.PATI_ID, SafeUtils.getUserID(getContext()));
parameters.put(Constant.REPORT_DATE, "'"+SafeUtils.getCurrentDate(getContext())+"'");
parameters.put(Constant.REP_TITLE, fileTitle);
parameters.put(Constant.IMG_EXTENTION_STATUS, "");
parameters.put(Constant.PATIENT_APPO_ID, patientAppointMentId);
new Thread(new Runnable() {
public void run() {
runOnUiThread(new Runnable() {
public void run() {
}
});
int response = uploadFile(getPath(imagePathUri), parameters);
System.out.println("RES : " + response);
}
}).start();
}
public String getPath(Uri uri) {
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String picturePath = cursor.getString(column_index);
return cursor.getString(column_index);
}
public int uploadFile(String sourceFileUri, Map<String, String> parmas) {
String upLoadServerUri = WebServices.LOCAL_UPLOAD_REPORTS;
String fileName = sourceFileUri;
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;
File sourceFile = new File(sourceFileUri);
InputStream inputStream = null;
if (!sourceFile.isFile()) {
Log.e("uploadFile", "Source File Does not exist");
return 0;
}
try { // open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL url = new URL(upLoadServerUri);
conn = (HttpURLConnection) url.openConnection(); // Open a HTTP connection to the URL
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("file", fileName);
dos = new DataOutputStream(conn.getOutputStream());
String name="_rep"+SafeUtils.getCurrentDateForName(getContext())+SafeUtils.getUserID(getContext());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"file\";filename=\""+ name+".png" + "\"" + lineEnd);
dos.writeBytes("Content-Type: " + "images/png" + lineEnd);
dos.writeBytes("Content-Transfer-Encoding: binary" + lineEnd);
dos.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available(); // create a buffer of maximum size
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);
// Upload POST Data
Iterator<String> keys = parmas.keySet().iterator();
while (keys.hasNext()) {
String key = keys.next();
String value = parmas.get(key);
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"" + key + "\"" + lineEnd);
dos.writeBytes("Content-Type: text/plain" + lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes(value);
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){
runOnUiThread(new Runnable() {
public void run() {
//tv.setText("File Upload Completed.");
Toast.makeText(getContext(), "File Upload Complete.", Toast.LENGTH_SHORT).show();
dialog.dismiss();
finish();
}
});
}
inputStream = conn.getInputStream();
report_id = this.convertStreamToString(inputStream);
//close the streams //
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
dialog.dismiss();
ex.printStackTrace();
Toast.makeText(getContext(), "MalformedURLException", Toast.LENGTH_SHORT).show();
Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
} catch (Exception e) {
dialog.dismiss();
e.printStackTrace();
Toast.makeText(getContext(), "Exception : " + e.getMessage(), Toast.LENGTH_SHORT).show();
Log.e("Upload file", "Exception : " + e.getMessage(), e);
}
dialog.dismiss();
return serverResponseCode;
}
private String convertStreamToString(InputStream inputStream) {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}

How to post data using multipart?

I develop one app. In my app i take one image from camera or one from gallery. I want to post image to server using Multipart but image not post it. My post data is below
{
"suggested_item" :{
"name": "apple",
"description" : "nice apple",
"image": "image.png"
}
}
My java code is
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PICK_FROM_CAMERA) {
try{
if(resultCode == -1){
File file = new File(Environment.getExternalStorageDirectory()+File.separator +"image.png");
bitmap = loadBitmap(file);
iv_pic.setImageBitmap(bitmap);
try {
Uri tempUri = getImageUri(getActivity(), bitmap);
Log.i(TAG,"onActivityResult PICK_FROM_CAMERA, tempUri : "+tempUri);
//uploadFile(tempUri + "" + System.currentTimeMillis()+".png");
} catch (Exception e) {
e.printStackTrace();
}
}else{
//setResult(RESULT_CANCELED);
//Activity.this.finish();
}
}catch(Exception e){
e.printStackTrace();
}
}else if (requestCode == PICK_FROM_GALLERY) {
try{
//Log.i(TAG,"onActivityResult PICK_FROM_GALLERY, data : "+data);
if(data !=null){
bitmap = null;
try {
bitmap = new BitmapDrawable(MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), data.getData())).getBitmap();
iv_pic.setImageBitmap(bitmap);
try {
Uri tempUri = getImageUri(getActivity(), bitmap);
Log.i(TAG,"onActivityResult PICK_FROM_GALLERY, tempUri : "+tempUri);
//uploadFile(tempUri + "" + System.currentTimeMillis()+".png");
} catch (Exception e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}else{
//setResult(RESULT_CANCELED);
//Activity.this.finish();
}
}catch(Exception e){
e.printStackTrace();
}
}
}
public Uri getImageUri(Context context , Bitmap bitmap) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG , 100 , bytes);
String path = Images.Media.insertImage(context.getContentResolver() , bitmap , "Title" , null);
return Uri.parse(path);
}
please help me thanks in advance.
To send binary data you need to use addBinaryBody method of MultipartEntityBuilder. Sample of attaching:
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
//Image attaching
MultipartEntityBuilder multipartEntity = MultipartEntityBuilder.create();
File file;
multipartEntity.addBinaryBody("someName", file, ContentType.create("image/jpeg"), file.getName());
//Json string attaching
String json;
multipartEntity.addPart("someName", new StringBody(json, ContentType.TEXT_PLAIN));
Then make request as usual:
HttpPut put = new HttpPut("url");
put.setEntity(multipartEntity.build());
HttpResponse response = client.execute(put);
int statusCode = response.getStatusLine().getStatusCode();
I suggest using retrofit.
Posting multipart will be something like this:
#Multipart
#PUT("user/photo")
Call<User> updateUser(#Part("photo") RequestBody photo, #Part("description") RequestBody description);
Refer to this question for more details.
This is a good tutorial to check if you are not familiar to retrofit.
Here I am Posting Full Code for Upload Image Using HTTP on Server also PHP code for understanding,
Class File
package com.stackexmples;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.AppCompatButton;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
/**
* Created by windws on 26-Mar-16.
*/
public class UploadImage extends AppCompatActivity implements View.OnClickListener {
private static final int REQUEST_TAKE_GALLERY_VIDEO = 11;
private static final String TAG = "UploadMultipleFile";
private AppCompatButton btnUploadFiles;
private AppCompatButton bntSelectImage;
private String filemanagerstring;
private String selectedImagePath="";
private TextView tvVideoList;
private TextView tvImageList;
private int selected = 0;
private LinearLayout ll;
private int count = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload_multiple_file);
initView();
initListener();
}
private void initView() {
btnUploadFiles = (AppCompatButton) findViewById(R.id.btnUploadFiles);
bntSelectImage = (AppCompatButton) findViewById(R.id.bntSelectImage);
}
private void initListener() {
btnUploadFiles.setOnClickListener(this);
bntSelectImage.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (v == btnUploadFiles) {
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
uploadFile("Data you want to sent");
}
});
thread.start();
} else if (v == bntSelectImage) {
selectImage();
}
}
private void selectImage() {
selected = 1;
Intent intent = new Intent();
intent.setType("Image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Image"), REQUEST_TAKE_GALLERY_VIDEO);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == REQUEST_TAKE_GALLERY_VIDEO) {
Log.d(TAG, "Called-->onActivityResultCalled");
Uri selectedImageUri = data.getData();
Log.d(TAG, "selectedImageUri-->" + selectedImageUri);
selectedImagePath = selectedImageUri.toString().replace("file://", "");
}
}
super.onActivityResult(requestCode, resultCode, data);
}
public String uploadFile(String req) {
// TODO Auto-generated method stub
String serverResponseMessage = "";
String response_return = "";
Log.d("first str is:", req);
String urlString = "http://192.168.1.32/TestUpload/upload.php";
URL imageUrl = null;
try {
imageUrl = new URL(urlString); // get WebService_URL
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
// generating byte[] boundary here
HttpURLConnection conn = null;
DataOutputStream outputStream = null;
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 10 * 1024 * 1024;
try {
int serverResponseCode;
conn = (HttpURLConnection) imageUrl.openConnection();
conn.setConnectTimeout(10000);
conn.setReadTimeout(10000);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
outputStream = new DataOutputStream(conn.getOutputStream());
//////////////////////////////////////////////////////
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"json\"" + lineEnd);
outputStream.writeBytes("Content-Type: text/plain;charset=UTF-8" + lineEnd);
outputStream.writeBytes("Content-Length: " + req.length() + lineEnd);
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(req + lineEnd);
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
try {
FileInputStream fileInputStream = new FileInputStream(selectedImagePath);
String lastOne = "temp";
/////////////////////////////////////////////
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: attachment; name=\"imageKey" + "\";" + " filename=" + lastOne +".jpg" + lineEnd); // pass key & value of photo
/*outputStream.writeBytes("Content-Type: application/octet-stream" + lineEnd);*/
outputStream.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available(); // photo size bytes
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);
Log.d("posttemplate", "connection outputstream size is " + outputStream.size());
fileInputStream.close();
} catch (OutOfMemoryError o) {
}
outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
serverResponseCode = conn.getResponseCode();
serverResponseMessage = conn.getResponseMessage();
InputStream is = conn.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response1 = new StringBuffer();
while ((line = rd.readLine()) != null) {
response1.append(line);
response1.append('\r');
}
rd.close();
response_return = response1.toString();
Log.d("posttemplate", "server response code " + serverResponseCode);
Log.d("posttemplate", "server response message "
+ serverResponseMessage);
outputStream.flush();
outputStream.close();
conn.disconnect();
} catch (MalformedURLException e) {
Log.d("posttemplate", "malformed url", e);
} catch (IOException e) {
Log.d("posttemplate", "ioexception", e);
}
Log.d("response--->", "****" + response_return);
return response_return;
}
}
Layout File
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.materialexample.UploadMultipleFile.UploadMultipleFile">
<android.support.v7.widget.AppCompatButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btnUploadFiles"
android:text="Upload Files" />
<LinearLayout
android:id="#+id/linearLayout1"
android:orientation="vertical"
android:layout_below="#id/btnUploadFiles"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.AppCompatButton
android:id="#+id/bntSelectImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Select Image" />
</LinearLayout>
</RelativeLayout>
PHP Code For Understanding
<?php
$file_path = "uploads/";
$file_path = $file_path . basename( $_FILES['imageKey']['name']);
if(move_uploaded_file($_FILES['imageKey']['tmp_name'], $file_path)) {
echo "success";
} else{
echo "fail";
}
if(isset($_REQUEST['json'])){
echo "text is-->".$_REQUEST['json'];
}
?>

org.json.JSONException: End of input at character 0 of

I am trying to upload video to server,but whenever I am trying to upload response is showing null null and in logcat it shows org.json.JSONException: End of input at character 0 of,instead of my response status:success msg:video uploaded..can any body tell me what is my mistake?
public class VideoUpload extends Activity{
MediaController mc;
private static int SELECT_PICTURE = 1;
private String selectedImagePath="";
TextView messageText;
Button uploadButton;
int serverResponseCode = 0;
ProgressDialog dialog = null;
private static final String TAG_SUCCESS = "status";
private static final String TAG_MSG = "msg";
String imgs;
String btns;
String upLoadServerUri = null;
ThreadPolicy th = new ThreadPolicy.Builder().permitAll().build();
final String uploadFilePath = Environment.getExternalStorageDirectory().getPath();
private Button buttonLoadImage;
private VideoView img;
private String User_ID;
private String sta;
private String msg;
private HttpURLConnection conn = null;
private String result="";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_video);
StrictMode.setThreadPolicy(th);
User_ID=this.getIntent().getStringExtra("id");
System.out.println("photo upload user id"+User_ID);
img = (VideoView)findViewById(R.id.imgViewvid);
mc = new MediaController(this);
mc.setAnchorView(img);
buttonLoadImage = (Button) findViewById(R.id.buttonLoadvid);
buttonLoadImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent();
intent.setType("video/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Picture"), SELECT_PICTURE);
}
});
uploadButton = (Button)findViewById(R.id.uploadButtonvid);
messageText = (TextView)findViewById(R.id.messageTextvid);
uploadButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dialog = ProgressDialog.show(VideoUpload.this, "", "Uploading file...", true);
new Thread(new Runnable() {
public void run() {
runOnUiThread(new Runnable() {
public void run() {
messageText.setText("uploading started.....");
}
});
uploadFile(selectedImagePath);
}
}).start();
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK)
{
if (requestCode == SELECT_PICTURE)
{
Uri mVideoURI = data.getData();
selectedImagePath = getPath(mVideoURI);
messageText.setText(selectedImagePath);
System.out.println(requestCode);
System.out.println("Image Path : " + selectedImagePath);
img.setVideoURI(mVideoURI);
}
}
}
#SuppressWarnings("deprecation")
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
public int uploadFile(String sourceFileUri) {
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
File sourceFile = new File(sourceFileUri);
if (!sourceFile.isFile()) {
dialog.dismiss();
Log.e("uploadFile", "Source File not exist :"
+ selectedImagePath);
runOnUiThread(new Runnable() {
public void run() {
messageText.setText("Source File not exist :"
+ selectedImagePath);
}
});
return 0;
}
else
{
try {
btns=uploadButton.getTag().toString();
System.out.println(btns);
String fileName = sourceFileUri;
File f = new File(selectedImagePath);
imgs= f.getName();
System.out.println(imgs);
upLoadServerUri = "http://mywebsitename.com/webservice/addvideo?version=apps&user_login_id="+User_ID+"&video_1="+imgs+"&action="+btns;
FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL url = new URL(upLoadServerUri);
System.out.println(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("video_1", imgs);
conn.setRequestProperty("user_login_id", User_ID);
conn.setRequestProperty("action", btns);
conn.setRequestProperty("version", "apps");
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"type\""
+ lineEnd);
dos.writeBytes(lineEnd);
// assign value
dos.writeBytes("version=apps");
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("user_login_id="+User_ID);
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("action="+btns);
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
// send image
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name='video_1';filename='"
+ imgs + "'" + 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){
runOnUiThread(new Runnable() {
#SuppressWarnings("deprecation")
public void run() {
try
{
DataInputStream dataIn = new DataInputStream(conn.getInputStream());
String inputLine;
while ((inputLine = dataIn.readLine()) != null)
{
result += inputLine;
System.out.println("Result : " + result);
}
JSONObject jobj = new JSONObject(result);
sta = jobj.getString("status");
msg = jobj.getString("msg");
System.out.println(sta + " >>>>>>> " + msg);
}
catch (Exception e)
{
e.printStackTrace();
}
Toast.makeText(VideoUpload.this, "" + sta + " : " + msg,
Toast.LENGTH_SHORT).show();
}
});
}
//close the streams //
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
dialog.dismiss();
ex.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
messageText.setText("MalformedURLException Exception : check script url.");
Toast.makeText(VideoUpload.this, "MalformedURLException", Toast.LENGTH_SHORT).show();
}
});
Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
} catch (Exception e) {
dialog.dismiss();
e.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
messageText.setText("Got Exception : see logcat ");
Toast.makeText(VideoUpload.this, "Got Exception : see logcat ",
Toast.LENGTH_SHORT).show();
}
});
Log.e("Upload file to server Exception", "Exception : "
+ e.getMessage(), e);
}
dialog.dismiss();
return serverResponseCode;
} // End else block
}
You are getting the org.json.JSON Exception : End of input at character 0 Because, you got null response which generated that exception.
So, Check your result string before convert in to JSONObject.
JSONObject jobj = new JSONObject(result); // Check this result string.
Again answer for Request.
Haresh Chhelana Answer is correct.
BufferedReader r = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder result = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
result.append(line);
}
JSONObject jobj = new JSONObject(result.toString());
Thanks.
Try to use BufferedReader :
BufferedReader r = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder result = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
result.append(line);
}

Uploading an image to a server in Android app

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);
}
}

Categories

Resources