how to capture images and post using json in android - 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

Related

How to choose document and image file from internal storage and upload to server?

I want to choose the media (image or document, either in pdf or docx format) file from internal storage and upload to server and also show the thumbnail of media file.
This code would help to upload the media (image or document, either in pdf or docx format) file from internal storage and upload to server.
for choose the file from internal :
Intent intent = new Intent();
//sets the select file to all types of files
intent.setType("*/*");
//allows to select data and return it
intent.setAction(Intent.ACTION_GET_CONTENT);
//starts new activity to select file and return data
startActivityForResult(Intent.createChooser(intent,"Choose File to Upload.."),PICK_FILE_REQUEST);
getting the file from:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == Activity.RESULT_OK){
if(requestCode == PICK_FILE_REQUEST){
if(data == null){
//no data present
return;
}
Uri selectedFileUri = data.getData();
selectedFilePath = FilePath.getPath(this,selectedFileUri);
Log.i(TAG,"Selected File Path:" + selectedFilePath);
if(selectedFilePath != null && !selectedFilePath.equals("")){
tvFileName.setText(selectedFilePath);
}else{
Toast.makeText(this,"Cannot upload file to server",Toast.LENGTH_SHORT).show();
}
}
}
}
Upload the file to server
public int uploadFile(final String selectedFilePath){
int serverResponseCode = 0;
HttpURLConnection connection;
DataOutputStream dataOutputStream;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead,bytesAvailable,bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
File selectedFile = new File(selectedFilePath);
String[] parts = selectedFilePath.split("/");
final String fileName = parts[parts.length-1];
if (!selectedFile.isFile()){
dialog.dismiss();
runOnUiThread(new Runnable() {
#Override
public void run() {
tvFileName.setText("Source File Doesn't Exist: " + selectedFilePath);
}
});
return 0;
}else{
try{
FileInputStream fileInputStream = new FileInputStream(selectedFile);
URL url = new URL(SERVER_URL);
connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);//Allow Inputs
connection.setDoOutput(true);//Allow Outputs
connection.setUseCaches(false);//Don't use a cached Copy
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("ENCTYPE", "multipart/form-data");
connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
connection.setRequestProperty("uploaded_file",selectedFilePath);
//creating new dataoutputstream
dataOutputStream = new DataOutputStream(connection.getOutputStream());
//writing bytes to data outputstream
dataOutputStream.writeBytes(twoHyphens + boundary + lineEnd);
dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
+ selectedFilePath + "\"" + lineEnd);
dataOutputStream.writeBytes(lineEnd);
//returns no. of bytes present in fileInputStream
bytesAvailable = fileInputStream.available();
//selecting the buffer size as minimum of available bytes or 1 MB
bufferSize = Math.min(bytesAvailable,maxBufferSize);
//setting the buffer as byte array of size of bufferSize
buffer = new byte[bufferSize];
//reads bytes from FileInputStream(from 0th index of buffer to buffersize)
bytesRead = fileInputStream.read(buffer,0,bufferSize);
//loop repeats till bytesRead = -1, i.e., no bytes are left to read
while (bytesRead > 0){
//write the bytes read from inputstream
dataOutputStream.write(buffer,0,bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable,maxBufferSize);
bytesRead = fileInputStream.read(buffer,0,bufferSize);
}
dataOutputStream.writeBytes(lineEnd);
dataOutputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
serverResponseCode = connection.getResponseCode();
String serverResponseMessage = connection.getResponseMessage();
Log.i(TAG, "Server Response is: " + serverResponseMessage + ": " + serverResponseCode);
//response code of 200 indicates the server status OK
if(serverResponseCode == 200){
runOnUiThread(new Runnable() {
#Override
public void run() {
tvFileName.setText("File Upload completed.\n\n You can see the uploaded file here: \n\n" + "http://coderefer.com/extras/uploads/"+ fileName);
}
});
}
//closing the input and output streams
fileInputStream.close();
dataOutputStream.flush();
dataOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(NewClassPdf.this,"File Not Found",Toast.LENGTH_SHORT).show();
}
});
} catch (MalformedURLException e) {
e.printStackTrace();
Toast.makeText(NewClassPdf.this, "URL error!", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(NewClassPdf.this, "Cannot Read/Write File!", Toast.LENGTH_SHORT).show();
}
dialog.dismiss();
return serverResponseCode;
}
}
this code help me to upload the file to server(all files).

FileNotFoundException while uploading a file from the SD card to a server

I got a FileNotFoundException error.
Code:
File getpath=Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES);
String dir= getpath.getAbsolutePath();
Log.e("filename of dir",dir);
//"/storage/emulated/0/Movies/"
try {
FileInputStream fstrm = new FileInputStream(dir+filename);
VideoFileUploadNew hfu = new VideoFileUploadNew( ServerURL.VIDEO_UPLOAD, filename);
upflag = hfu.Send_Now(fstrm);
Log.e("filename of v up",filename);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
public class VideoFileUploadNew implements Runnable {
URL connectURL;
String responseString;
String Title;
String fileName;
String Description;
byte[ ] dataToServer;
FileInputStream fileInputStream = null;
public VideoFileUploadNew(String urlString, String file){
try{
connectURL = new URL(urlString);
fileName = file;
}catch(Exception ex){
Log.i("HttpFileUpload","URL Malformatted");
}
}
public Boolean Send_Now(FileInputStream fStream){
fileInputStream = fStream;
return Sending();
}
Boolean Sending(){
System.out.println("file Name is :"+fileName);
String iFileName = fileName;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
String Tag="fSnd";
try
{
Log.e(Tag,"Starting Http File Sending to URL");
// Open a HTTP connection to the URL
HttpURLConnection conn = (HttpURLConnection)connectURL.openConnection();
// Allow Inputs
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);
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes("Content-Disposition: form-data; name=\"vfile\";filename=\"" + iFileName +"\"" + lineEnd);
dos.writeBytes(lineEnd);
Log.e(Tag,"Headers are written");
// create a buffer of maximum size
int bytesAvailable = fileInputStream.available();
int maxBufferSize =9024;
int bufferSize = Math.min(bytesAvailable, maxBufferSize);
byte[ ] buffer = new byte[bufferSize];
// read file and write it into form...
int 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);
// close streams
fileInputStream.close();
dos.flush();
Log.e(Tag,"File Sent, Response: "+String.valueOf(conn.getResponseCode()));
InputStream is = conn.getInputStream();
// retrieve the response from server
int ch;
StringBuffer b =new StringBuffer();
while( ( ch = is.read() ) != -1 ){ b.append( (char)ch ); }
String s=b.toString();
Log.i("Response",s);
dos.close();
if(String.valueOf(conn.getResponseCode()).equals("200"))
{
return true;
}else{
return false;
}
}
catch (MalformedURLException ex)
{
Log.e(Tag, "URL error: " + ex.getMessage(), ex);
}
catch (IOException ioe)
{
Log.e(Tag, "IO error: " + ioe.getMessage(), ioe);
}
return false;
}
#Override
public void run() {
}
}
Your question is still pretty vague, but one of the reasons this happens is- when you're fetching the relative URI of the File, but need the Absolute URI for the upload.
You can check out different FileUtil classes like this https://github.com/z0rawarr/AndroidUtilCode/blob/master/utilcode/src/main/java/com/blankj/utilcode/utils/FileUtils.java
Get the absolute path from the URI and use that to upload.
Also, do not forget to use the Debugger, and apply a breakpoint on uploadFile() to debug the URIs.

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

Cant able to Upload Images From Gallery (Crashes or Out Of Memory Occurs)

Opening The Gallery App
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
dialog1.dismiss();
startActivityForResult(Intent.createChooser(intent,"Select Picture"), SELECT_PICTURE);
After selecting Goes to OnActivityResult
selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
if(selectedImagePath==null)
{
Toast.makeText(MyProfileNewActivity.this, "Wrong File Please Select From Gallery", Toast.LENGTH_SHORT).show();
}
else
{
UploadProfilePicGallery uppg=new UploadProfilePicGallery();
uppg.execute();
}**
Starts The Asynctask to Upload the Image to the Server using AndroidMultiPartEntity
public class UploadProfilePicGallery extends AsyncTask<Void,String,String>
{
#Override
protected String doInBackground(Void... voids) {
//sourceFileUri.replace(sourceFileUri, "jagan");
//
int day, month, year;
int second, minute, hour;
GregorianCalendar date = new GregorianCalendar();
day = date.get(Calendar.DAY_OF_MONTH);
month = date.get(Calendar.MONTH);
year = date.get(Calendar.YEAR);
second = date.get(Calendar.SECOND);
minute = date.get(Calendar.MINUTE);
hour = date.get(Calendar.HOUR);
String name = (hour + "" + minute + "" + second + "" + day + "" + (month + 1) + "" + year);
String tag = name + ".jpg";
String fileName = selectedImagePath.replace(selectedImagePath, tag);
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(selectedImagePath);
try {
Bitmap bmp = BitmapFactory.decodeFile(sourceFile.getAbsolutePath());
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] bitmapdata = bos.toByteArray();
bmp.compress(Bitmap.CompressFormat.JPEG, 10, bos);
bmp.compress(Bitmap.CompressFormat.JPEG, 10, bos);
bmp = getResizedBitmap(bmp, 100);
bitmapdata=bos.toByteArray();
bProfileBitmap=bmp;
FileOutputStream fos= null;
try {
fos = new FileOutputStream(sourceFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
fos.write(bitmapdata);
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
catch(OutOfMemoryError o)
{
return "Out Of Memory Error";
}
if (!sourceFile.isFile()) {
// dialog.dismiss();
Log.e("uploadFile", "Source File not exist :" + "");
result="file missing";
return result;
} else {
try {
// open a URL connection to the Servlet
File sourceFile1 = new File(selectedImagePath);
FileInputStream fileInputStream = new FileInputStream(sourceFile1);
URL url = new URL(URLPath+"FileUploadGallery.php");
// 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); //===============
session.setPicName(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) {
result= "File Upload Completed";
}
//close the streams //
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
ex.printStackTrace();
result ="MalformedURLException";
Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
} catch (Exception e) {
e.printStackTrace();
result = "Exception";
Log.e("Upload file to server Exception", "Exception : " + e.getMessage(), e);
}
return result;
}
}
Note The Error Comes Only When The User Selects the image which is taken by the camera... Other then that, downloaded images are able to Upload from Gallery. (Sometimes Crashes Sometimes OutOfMemoryErrorOccurs)
Please Give Me a solution i worked on this more then 3 days i cant able to find out the problem........
If You Had any other codes which is really working fine Please Share with me....
Just try this by change your Intent.May it help
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE);

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