How to post data using multipart? - android

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'];
}
?>

Related

File do not exist Error - Android

I have this code that allows me to select a file and upload it to a server.
Whenever I test it, it always says "File do not exist", I test it with different file explorer, but it's always the same message.
This is UploadFilesToServer.java
package com.example.hp.test;
/**
* Created by Haroun SMIDA on 8/8/2015.
*/
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.OpenableColumns;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.example.hp.test.app.AppConfig;
public class UploadFilesToServer extends Activity implements OnClickListener {
private TextView uploadStatus;
private Button btnUploadFile;
private Button btnSelectFIle;
private int serverResponseCode = 0;
private ProgressDialog dialog = null;
private String upLoadServerUri = null;
private static final int FILE_SELECT_CODE = 0;
/**
* ******* File Path ************
*/
private String uploadFilePath = null;
private String uploadFileName = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_uploadfile);
btnUploadFile = (Button) findViewById(R.id.btnUploadFile);
btnUploadFile.setOnClickListener(this);
btnSelectFIle = (Button) findViewById(R.id.btnSelectFile);
btnSelectFIle.setOnClickListener(this);
uploadStatus = (TextView) findViewById(R.id.uploadStatus);
/************* Php script path ****************/
upLoadServerUri = AppConfig.URL_UPLOAD;
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnSelectFile:
selectFile();
break;
case R.id.btnUploadFile:
dialog = ProgressDialog.show(UploadFilesToServer.this, "", "Uploading file...", true);
new Thread(new Runnable() {
public void run() {
runOnUiThread(new Runnable() {
public void run() {
uploadStatus.setText("uploading started.....");
}
});
Log.i("File Path ", uploadFilePath);
Log.i("File Name ", uploadFileName);
uploadFile(uploadFilePath);
}
}).start();
;
break;
default:
break;
}
}
public int uploadFile(String sourceFileUri) {
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 = 1024 * 1024;
File sourceFile = new File(sourceFileUri);
Log.i("File Uri ", sourceFileUri);
Log.i("File ", sourceFile.toString());
if (!sourceFile.exists()) {
dialog.dismiss();
Log.e("uploadFile", "Source File not exist :"
+ uploadFilePath);
runOnUiThread(new Runnable() {
public void run() {
uploadStatus.setText("Source File not exist :"
+ uploadFilePath);
}
});
return 0;
} else {
try {
// open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL url = new URL(upLoadServerUri);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true); // Allow Inputs
conn.setDoOutput(true); // Allow Outputs
conn.setUseCaches(false); // Don't use a Cached Copy
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("uploaded_file", fileName);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=uploaded_file;filename=" + fileName + "" + lineEnd);
dos.writeBytes(lineEnd);
// create a buffer of maximum size
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// Responses from the server (code and message)
serverResponseCode = conn.getResponseCode();
String serverResponseMessage = conn.getResponseMessage();
Log.i("uploadFile", "HTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode);
if (serverResponseCode == 200) {
runOnUiThread(new Runnable() {
public void run() {
String msg = "File Upload Completed.\n\n See uploaded file here : \n\n"
+ " http://www.androidexample.com/media/uploads/"
+ uploadFileName;
uploadStatus.setText(msg);
Toast.makeText(UploadFilesToServer.this, "File Upload Complete.",
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() {
uploadStatus.setText("MalformedURLException Exception : check script url.");
Toast.makeText(UploadFilesToServer.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() {
uploadStatus.setText("Got Exception : see logcat ");
Toast.makeText(UploadFilesToServer.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
}
private void selectFile() {
Intent intent = new Intent();
intent.setType("*/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(Intent.createChooser(intent, "Select File"), FILE_SELECT_CODE);
uploadStatus.setText("Uploading file path :- '" + uploadFilePath+ "'");
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == FILE_SELECT_CODE) {
Uri selectedFileUri = data.getData();
String uriString = selectedFileUri.toString();
File fileToUpload = new File(uriString);
uploadFilePath = fileToUpload.getAbsolutePath();
if (uriString.startsWith("content://")) {
Cursor cursor = null;
try {
cursor = getContentResolver().query(selectedFileUri, null, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
uploadFileName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
}
} finally {
cursor.close();
}
} else if (uriString.startsWith("file://")) {
uploadFileName = fileToUpload.getName();
}
}
}
}
}
What is the right method that allows me to get the right path for the selected file?

How can send images from Android Application to Server?

I want to store images in a server via POST, the images that are sent are sent from the local storage cell, this my code asynchronous class in Android :
class ImageUpload extends AsyncTask<Void, Void, String>{
#Override
protected String doInBackground(Void... var) {
System.out.println(incidentId);
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;
String[] q = mCurrentPhotoPath.split("/");
int idx = q.length - 1;
try {
File file = new File(mCurrentPhotoPath);
FileInputStream fileInputStream = new FileInputStream(file);
URL url = new URL(url_add_attachment);
connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "multipart/form-data; charset=UTF-8");
connection.setRequestProperty("Accept", "application/json");
outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.writeBytes(twoHyphens + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"" + "file" + "\"; filename=\"" + q[idx] + "\"" + lineEnd);
outputStream.writeBytes("Content-Type: " + "image" + 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);
outputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
outputStream.writeBytes(lineEnd);
try {
outputStream.writeBytes(twoHyphens + lineEnd);
//outputStream.writeBytes("Content-Disposition: form-data; name=\"" + key + "\"" + lineEnd);
outputStream.writeBytes("Content-Type: text/plain" + lineEnd);
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(lineEnd);
//}
outputStream.writeBytes(twoHyphens + twoHyphens + lineEnd);
} catch (Exception e) {
e.printStackTrace();
}
int status = connection.getResponseCode();
InputStream in;
if(status >= HttpStatus.SC_BAD_REQUEST)
in = connection.getErrorStream();
else
in = connection.getInputStream();
inputStream = connection.getInputStream();
result = convertStreamToString(in);
fileInputStream.close();
inputStream.close();
outputStream.flush();
outputStream.close();
}catch(Exception e){
e.printStackTrace();
}
return result;
}
}
The server throws 400 error response also send me the exception :
java.io.FileNotFoundException: http://10.0.2.2/app_dev.php/incidents/8/attachments
MainActivity.java
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener{
private TextView messageText;
private Button uploadButton, btnselectpic;
private ImageView imageview;
private int serverResponseCode = 0;
private ProgressDialog dialog = null;
private String upLoadServerUri = null;
private String imagepath=null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
uploadButton = (Button)findViewById(R.id.uploadButton);
btnselectpic = (Button)findViewById(R.id.button_selectpic);
messageText = (TextView)findViewById(R.id.messageText);
imageview = (ImageView)findViewById(R.id.imageView_pic);
btnselectpic.setOnClickListener(this);
uploadButton.setOnClickListener(this);
upLoadServerUri = "http://10.0.2.2/uploads/UploadToServer.php";
ImageView img= new ImageView(this);
}
#Override
public void onClick(View arg0) {
if(arg0==btnselectpic)
{
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Complete action using"), 1);
}
else if (arg0==uploadButton) {
dialog = ProgressDialog.show(MainActivity.this, "", "Uploading file...", true);
messageText.setText("uploading started.....");
new Thread(new Runnable() {
public void run() {
uploadFile(imagepath);
}
}).start();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1 && resultCode == RESULT_OK) {
//Bitmap photo = (Bitmap) data.getData().getPath();
Uri selectedImageUri = data.getData();
imagepath = getPath(selectedImageUri);
Bitmap bitmap=BitmapFactory.decodeFile(imagepath);
imageview.setImageBitmap(bitmap);
messageText.setText("Uploading file path:" +imagepath);
}
}
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) {
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);
if (!sourceFile.isFile()) {
dialog.dismiss();
Log.e("uploadFile", "Source File not exist :"+imagepath);
runOnUiThread(new Runnable() {
public void run() {
messageText.setText("Source File not exist :"+ imagepath);
}
});
return 0;
}
else
{
try {
// open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL url = new URL(upLoadServerUri);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true); // Allow Inputs
conn.setDoOutput(true); // Allow Outputs
conn.setUseCaches(false); // Don't use a Cached Copy
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("uploaded_file", fileName);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
+ fileName + "\"" + lineEnd);
dos.writeBytes(lineEnd);
// create a buffer of maximum size
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// Responses from the server (code and message)
serverResponseCode = conn.getResponseCode();
String serverResponseMessage = conn.getResponseMessage();
Log.i("uploadFile", "HTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode);
if(serverResponseCode == 200){
runOnUiThread(new Runnable() {
public void run() {
String msg = "File Upload Completed.\n\n See uploaded file here : \n\n"
+" F:/wamp/wamp/www/uploads";
messageText.setText(msg);
Toast.makeText(MainActivity.this, "File Upload Complete.", 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(MainActivity.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(MainActivity.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
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<ImageView
android:id="#+id/imageView_pic"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_gravity="center"
android:src="#drawable/ic_launcher" />
<Button
android:id="#+id/button_selectpic"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Select Picture" />
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Click To Upload File"
android:id="#+id/uploadButton"
/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text=""
android:id="#+id/messageText"
android:textColor="#000000"
android:textStyle="bold"
/>
</LinearLayout>
Mainfest file::
<uses-permission android:name="android.permission.INTERNET"/>
UploadToServer.php
<?php
$file_path = "../image upload folder name here/";
$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";
}
?>
You can pass your server url in following method to upload any file.Change file parameter in given code with your actual file.
public static HttpResponse uploadFile(String url) throws ClientProtocolException, IOException {
try {
// the file to be posted
String textFile = Environment.getExternalStorageDirectory() + "/file.txt";
// /.v(TAG, "textFile: " + textFile);
// Log.v(TAG, "postURL: " + url);
HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is
// established.
// The default value is zero, that means the timeout is not used.
int timeoutConnection = 10000;
// HttpConnectionParams.setConnectionTimeout(httpParameters,
// timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 5000;
// HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
HttpClient httpClient = new DefaultHttpClient(httpParameters);
// post header
HttpPost httpPost = new HttpPost(url);
File file = new File(textFile);
FileBody fileBody = new FileBody(file);
MultipartEntityBuilder mBuilder = MultipartEntityBuilder.create();
mBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
mBuilder.addPart("fileUpload", fileBody);
httpPost.setEntity(mBuilder.build());
return httpClient.execute(httpPost);
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

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 upload image to server?

I have searched many sites to know how to upload image to server.I have seen one sample example.But it is not reading imaging from internal memory of phone.
I have included MainActivity.java file.Any suggestions please..
MainActivity.java
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener{
private TextView messageText;
private Button uploadButton, btnselectpic;
private ImageView imageview;
private int serverResponseCode = 0;
private ProgressDialog dialog = null;
private String upLoadServerUri = null;
private String imagepath=null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
uploadButton = (Button)findViewById(R.id.uploadButton);
messageText = (TextView)findViewById(R.id.messageText);
btnselectpic = (Button)findViewById(R.id.button_selectpic);
imageview = (ImageView)findViewById(R.id.imageView_pic);
btnselectpic.setOnClickListener(this);
uploadButton.setOnClickListener(this);
upLoadServerUri = "http://192.168.0.15/UploadToServer.php";
}
#Override
public void onClick(View arg0) {
if(arg0==btnselectpic)
{
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Complete action using"), 1);
}
else if (arg0==uploadButton) {
dialog = ProgressDialog.show(MainActivity.this, "", "Uploading file...", true);
messageText.setText("uploading started.....");
new Thread(new Runnable() {
public void run() {
uploadFile(imagepath);
}
}).start();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.v("Upload image", ""+data);
if (requestCode == 1 && resultCode == RESULT_OK) {
//Bitmap photo = (Bitmap) data.getData().getPath();
Uri selectedImageUri = data.getData();
imagepath = getPath(selectedImageUri);
Bitmap bitmap=BitmapFactory.decodeFile(imagepath);
imageview.setImageBitmap(bitmap);
messageText.setText("Uploading file path:" +imagepath);
}
}
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) {
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);
if (!sourceFile.isFile()) {
dialog.dismiss();
Log.e("uploadFile", "Source File not exist :"+imagepath);
runOnUiThread(new Runnable() {
public void run() {
messageText.setText("Source File not exist :"+ imagepath);
}
});
return 0;
}
else
{
try {
// open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL url = new URL(upLoadServerUri);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true); // Allow Inputs
conn.setDoOutput(true); // Allow Outputs
conn.setUseCaches(false); // Don't use a Cached Copy
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("uploaded_file", fileName);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
+ fileName + "\"" + lineEnd);
dos.writeBytes(lineEnd);
// create a buffer of maximum size
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// Responses from the server (code and message)
serverResponseCode = conn.getResponseCode();
String serverResponseMessage = conn.getResponseMessage();
Log.i("uploadFile", "HTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode);
if(serverResponseCode == 200){
runOnUiThread(new Runnable() {
public void run() {
String msg = "File Upload Completed.\n\n See uploaded file here : \n\n"
+" F:/wamp/wamp/www/uploads";
messageText.setText(msg);
Toast.makeText(MainActivity.this, "File Upload Complete.", 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(MainActivity.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(MainActivity.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
}
}
MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
multipartEntity.addPart("key", new StringBody("file"));
File file = new File(selectedImagePath);
multipartEntity.addPart("file", new FileBody(file));
httppost.setEntity(multipartEntity);
mHttpClient.execute(httppost, new PhotoUploadResponseHandler());
and the response methode:
private class PhotoUploadResponseHandler implements ResponseHandler<Object> {
#Override
public Object handleResponse(HttpResponse response)
throws ClientProtocolException, IOException {
HttpEntity r_entity = response.getEntity();
// String responseString = EntityUtils.toString(r_entity);
return null;
}
}
Use multipart in android, download httpmime-4.2.5.jar and add you libs folder http://grepcode.com/snapshot/repo1.maven.org/maven2/org.apache.httpcomponents/httpmime/4.2.5
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpPost httppost = new HttpPost("url");
File file = new File(filepath);
MultipartEntity mpEntity = new MultipartEntity();
ContentBody cbFile = new FileBody(file, "image/jpeg");
mpEntity.addPart("userfile", cbFile);
httppost.setEntity(mpEntity);
System.out.println("executing request " + httppost.getRequestLine());
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
try this code..
String url = "";
MultiValueMap<String, Object> parts = new LinkedMultiValueMap<String, Object>();
parts.add("file", new FileSystemResource(your filename path));
RestTemplate rest = RestUtil.getRestTemplate();
rest.postForObject(url, parts, returnclassname.class);
return null;
thank you..
The server side code remains the same for both browser based and mobile apps, to upload an file. File upload requires a multipart post request.
Uploading an image is same as uploading a file with a specified content type image/*. You can mimic the request using Apache's HttpClient. Also remember to perform the upload in the separate thread.
Here's an example.
Please check your android manifest file. Have u allowed all these in your manifest.?
Sorry I m missing some permissions please google them.
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

how to Upload image into server in Android?

I am trying to Upload image Capture by Camera into server. server send response code = 200 but Image is not upload into server.
Code is :
private boolean uploadData() {
int count = this.forumThreadsB.size();
for (int i = 0; i < count; i++)
{
if (isPhoto)
message = "Uploading Shared Items " + (i + 1) + " of " + count;
else
message = "Uploading Shared Items " + (i + 1) + " of " + count;
progressCount = (i * 1000)/count;
Hashtable<?, ?> threadD = (Hashtable<?, ?>)this.forumThreadsB.elementAt(i);
String onlinePath = "http://xyx.com/;
threadid = (String) threadD.get("devicethreadid");
Hashtable<String, String> pairs = new Hashtable<String, String>();
pairs.put("forumid", threadD.get("lmsforumid").toString());
pairs.put("topicid", threadD.get("lmsthreadid").toString());
pairs.put("clientid", LoginHelper.clientid);
String fullfilepath = threadD.get("offlinepath").toString();
int index = threadD.get("offlinepath").toString().lastIndexOf("/");
String filename = fullfilepath.substring(index + 1);
String filetype = "";
if (filename.toLowerCase().contains(".png"))
filetype = "image/png";
else if (filename.toLowerCase().contains(".jpg"))
filetype = "image/jpeg";
else if (filename.toLowerCase().contains(".mp4"))
filetype = "image/mp4";
else if (filename.toLowerCase().contains(".3gp"))
filetype = "image/3gpp";
String boundaryMessage = getBoundaryMessage(BOUNDARY, pairs, fullfilepath, filename, filetype);
String endBoundary = "\r\n--" + BOUNDARY + "--\r\n";
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;
try
{
URL url = new URL(onlinePath);
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+BOUNDARY);
dos = new DataOutputStream( conn.getOutputStream() );
dos.write( boundaryMessage.getBytes());
File file = new File(fullfilepath.substring(6));
FileInputStream fileInputStream = new FileInputStream(file);
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.write(endBoundary.getBytes());
dos.flush();
dos.close();
fileInputStream.close();
} catch (IOException ioe) {
Log.e("SyncUploadDownloadHelper", "Cannot upload file: " + ioe.getMessage(), ioe);
//return false;
}
// Read response
try {
int responseCode = conn.getResponseCode();
if(responseCode == 200){
SQLiteForumDAO forumDAO = new SQLiteForumDAO(mcontext) ;
ForumThreadDTO forumThreadDTO = forumDAO.selectThread(this.threadid);
if(downloadPath!=null && downloadPath.equalsIgnoreCase("null") && downloadPath.equalsIgnoreCase(""))
forumThreadDTO.offlinefilepath = downloadPath;
forumDAO.updateThread(forumThreadDTO);
}
} catch (IOException ioex) {
Log.e("SyncUploadDownloadHelper", "Upload file failed: " + ioex.getMessage(), ioex);
//return false;
} catch (Exception e) {
Log.e("SyncUploadDownloadHelper", "Upload file failed: " + e.getMessage(), e);
//return false;
}
if (i == (this.forumThreadsB.size() - 1)){
this.sendStatus = "true";
progressCount = 1000;
SyncUploadDownloadHelper.this.notifyObservers("SyncUploadDownloadHelper:UploadDataFinish");
}
else
SyncUploadDownloadHelper.this.notifyObservers("SyncUploadDownloadHelper:UploadData");
//return true;
}
return true;
}
Function :
private String getBoundaryMessage(String boundary, Hashtable<String, String> params, String fileField, String fileName, String fileType) {
StringBuffer res = new StringBuffer("--").append(boundary).append("\r\n");
Enumeration<String> keys = params.keys();
while(keys.hasMoreElements()) {
String key = (String)keys.nextElement();
String value = (String)params.get(key);
System.out.println(key + ": " + value);
res.append("Content-Disposition: form-data; name=\"").append(key).append("\"\r\n")
.append("\r\n").append(value).append("\r\n").append("--").append(boundary).append("\r\n");
}
res.append("Content-Disposition: form-data; name=\"").append("file").append("\"; filename=\"").append(fileName).append("\"\r\n")
.append("Content-Type: ").append(fileType).append("\r\n\r\n");
return res.toString();
}
in my Application I Capture Image and Save it to Database. path of save image is use to upload image file.
I using this:
public class HttpClient extends AsyncTask<Void, Integer, Long> {
private static final int PROGRESS_DIALOG = 0;
public ProgressDialog dialog;
public File file;
protected Long doInBackground(Void... params) {
for (File file : files) {
foto = "/sdcard/CameraExample/" + file.getName();
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(urll);
MultipartEntity mpEntity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
mpEntity.addPart("form_file", new FileBody(file, "image/jpeg"));
httppost.setEntity(mpEntity);
HttpResponse response;
try {
response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
}
if (resEntity != null) {
resEntity.consumeContent();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
protected void onPostExecute(Long unused) {
progressDialog.dismiss();
((Runnable) ctx ).run();
super.onPostExecute(unused);
}
protected void onPreExecute() {
progressDialog = new ProgressDialog(ctx);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setMessage("Загрузка фото...");
progressDialog.setProgress(0);
progressDialog.setMax(count);
progressDialog.show();
}
}
This code using that library:
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.apache.james.mime4j.message.Message;
You can find this in Google. If you don't find - i can send you this libraries.

Categories

Resources