I have EditProfilAcitivity if i click imageview will select from gallery and no have problem. I have problem id i click button upload.
package net.drieanto.lagidimana;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import net.drieanto.lagidimana.library.AlertDialogManager;
import net.drieanto.lagidimana.library.ConnectionDetector;
import net.drieanto.lagidimana.library.UserFunctions;
import android.app.ActionBar;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.MediaStore.MediaColumns;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class EditProfileActivity extends Activity {
UserFunctions userFunctions;
Button btnLogout, buttonsearch;
EditText editSearch;
private ListView list;
private ArrayAdapter<String> adapter;
private RibbonMenuView rbmView;
private Button test;
private ListView rbmListView;
private ListView rbmListView2;
private ArrayAdapter<String> adapt;
private ArrayAdapter<String> adapter2;
ListView list1;
LazyAdapter adapter1;
private static int RESULT_LOAD_IMAGE = 1;
// Alert dialog manager
AlertDialogManager alert = new AlertDialogManager();
// Connection detector
ConnectionDetector cd;
String selectedPath = "";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/**
* Dashboard Screen for the application
* */
// Check login status in database
userFunctions = new UserFunctions();
if (userFunctions.isUserLoggedIn(getApplicationContext())) {
setContentView(R.layout.editprofile);
if (android.os.Build.VERSION.SDK_INT >= 11){
ActionBar bar = getActionBar();
bar.setBackgroundDrawable(new ColorDrawable(Color.rgb(254,194,12)));
int actionBarTitleId = Resources.getSystem().getIdentifier("action_bar_title", "id", "android");
TextView actionBarTextView = (TextView)findViewById(actionBarTitleId);
actionBarTextView.setTypeface(null, Typeface.BOLD);
}
// Check if Internet present
cd = new ConnectionDetector(getApplicationContext());
if (!cd.isConnectingToInternet()) {
// Internet Connection is not present
alert.showAlertDialog(EditProfileActivity.this,
"Internet Connection Error",
"Please connect to working Internet connection", false);
// stop executing code by return
return;
}
/** Menu **/
rbmView = (RibbonMenuView) findViewById(R.id.ribbonMenuView1);
list = (ListView) findViewById(R.id.listView1);
ProgressDialog progressDialog = new ProgressDialog(
EditProfileActivity.this);
progressDialog.setMessage("Loading...");
EditProfileTask EditProfileTask = new EditProfileTask(
EditProfileActivity.this, progressDialog);
EditProfileTask.execute();
ImageView image = (ImageView) findViewById(R.id.gambarAvatar);
image.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
});
editSearch = (EditText) findViewById(R.id.search);
buttonsearch = (Button) findViewById(R.id.buttonsearch);
buttonsearch.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent search = new Intent(getApplicationContext(),
SearchActivity.class);
search.putExtra("data", editSearch.getText().toString());
search.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(search);
finish();
}
});
/**
* This is an exmaple button it calls "hideMenu()" after each click
* similiar to the Facebook or Google+ apps
* **/
btnLogout = (Button) findViewById(R.id.buttonLogout);
btnLogout.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
userFunctions.logoutUser(getApplicationContext());
Intent login = new Intent(getApplicationContext(),
LoginActivity.class);
login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(login);
// Closing dashboard screen
finish();
}
});
/**
* This is the most important ListView, updating the main list in
* the Activity
**/
final String[] items_list = { "Home", "Follower", "Request", "View Profile" };
adapt = new ArrayAdapter<String>(EditProfileActivity.this,
android.R.layout.simple_list_item_1, items_list);
rbmListView = (ListView) findViewById(R.id.rbm_listview);
rbmListView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
switch (position) {
case 0:
Intent dashboard = new Intent(getApplicationContext(),
DashboardActivity.class);
dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(dashboard);
finish();
break;
case 1:
Intent follower = new Intent(getApplicationContext(),
FollowerActivity.class);
follower.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(follower);
finish();
break;
case 2:
Intent request = new Intent(getApplicationContext(),
RequestActivity.class);
request.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(request);
finish();
break;
case 3:
Intent profil = new Intent(getApplicationContext(),
ProfilActivity.class);
profil.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(profil);
// Closing dashboard screen
finish();
break;
default:
break;
}
rbmView.hideMenu();
}
});
rbmListView.setAdapter(adapt);
} else {
// user is not logged in show login screen
Intent login = new Intent(getApplicationContext(),
LoginActivity.class);
login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(login);
// Closing dashboard screen
finish();
}
Button upload = (Button)findViewById(R.id.imguploadbtn);
upload.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
new ImageUpload().execute();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK
&& null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaColumns.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
selectedPath = getPath(selectedImage);
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
final String picturePath = cursor.getString(columnIndex);
cursor.close();
ImageView imageView = (ImageView) findViewById(R.id.gambarAvatar);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
}
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);
}
/*private void doFileUpload(){
HttpURLConnection conn = null;
DataOutputStream dos = null;
DataInputStream inStream = null;
String lineEnd = "rn";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;
String responseFromServer = "";
String urlString = "http://git.drieanto.net/upload/upload.php";
try
{
//------------------ CLIENT REQUEST
FileInputStream fileInputStream = new FileInputStream(new File(selectedPath) );
// open a URL connection to the Servlet
URL url = new URL(urlString);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.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);
dos = new DataOutputStream( conn.getOutputStream() );
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + selectedPath + "\"" + 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);
// close streams
Log.e("Debug","File is written");
fileInputStream.close();
dos.flush();
dos.close();
}
catch (MalformedURLException ex)
{
Log.e("Debug", "error: " + ex.getMessage(), ex);
}
catch (IOException ioe)
{
Log.e("Debug", "error: " + ioe.getMessage(), ioe);
}
//------------------ read the SERVER RESPONSE
try {
inStream = new DataInputStream ( conn.getInputStream() );
String str;
while (( str = inStream.readLine()) != null)
{
Log.e("Debug","Server Response "+str);
}
inStream.close();
}
catch (IOException ioex){
Log.e("Debug", "error: " + ioex.getMessage(), ioex);
}
}*/
/**
* Allows users, even API < 5, to use the back button
*
* public boolean onKeyDown(int keyCode, KeyEvent event) { switch (keyCode)
* { case KeyEvent.KEYCODE_BACK: rbmView.hideMenu(); break; default: return
* super.onKeyDown(keyCode, event); } return true; }
*/
/**
* Options Menu<br>
* example toggle
*/
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.test:
rbmView.toggleMenu();
break;
default:
return super.onOptionsItemSelected(item);
}
return true;
}
public void showEditError(int responseCode) {
int duration = Toast.LENGTH_LONG;
Context context = getApplicationContext();
Toast toast = Toast.makeText(context, "Terjadi Error", duration);
toast.show();
}
public void showEditSuccess(int responseCode) {
int duration = Toast.LENGTH_LONG;
Context context = getApplicationContext();
Toast toast = Toast.makeText(context, "Terjadi Error", duration);
toast.show();
}
class ImageUpload extends AsyncTask<Void, Void, String>{
#Override
protected void onProgressUpdate(Void... unsued) {
}
#Override
protected String doInBackground(Void... params) {
HttpURLConnection conn = null;
DataOutputStream dos = null;
DataInputStream inStream = null;
String lineEnd = "rn";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;
String responseFromServer = "";
String urlString = "http://lagidimana.net/upload/upload.php";
try
{
//------------------ CLIENT REQUEST
FileInputStream fileInputStream = new FileInputStream(new File(selectedPath) );
// open a URL connection to the Servlet
URL url = new URL(urlString);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.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);
dos = new DataOutputStream( conn.getOutputStream() );
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + selectedPath + "\"" + 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);
// close streams
Log.e("Debug","File is written");
fileInputStream.close();
dos.flush();
dos.close();
}
catch (MalformedURLException ex)
{
Log.e("Debug", "error: " + ex.getMessage(), ex);
}
catch (IOException ioe)
{
Log.e("Debug", "error: " + ioe.getMessage(), ioe);
}
//------------------ read the SERVER RESPONSE
try {
inStream = new DataInputStream ( conn.getInputStream() );
String str;
while (( str = inStream.readLine()) != null)
{
Log.e("Debug","Server Response "+str);
}
inStream.close();
}
catch (IOException ioex){
Log.e("Debug", "error: " + ioex.getMessage(), ioex);
}
return null;
}
}
}
upload.php file
<?php
// Where the file is going to be placed
$target_path = "uploads/";
/* Add the original filename to our target path.
Result is "uploads/filename.extension" */
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['uploadedfile']['name']).
" has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
echo "filename: " . basename( $_FILES['uploadedfile']['name']);
echo "target_path: " .$target_path;
}
?>
i have chmod 777 folder uploads/
Error Message in logcat in bottom, but i don't understand with this error. Maybe you have same problem.
06-14 21:46:35.339: E/Debug(13682): File is written
06-14 21:46:53.339: E/Debug(13682): Server Response There was an error uploading the file, please try again!filename: target_path: uploads/
please help thank's
You are calling the function doFileUpload from the Main UI thread. Android does not allow you to make Network calls on the main thread.
Build an Asynctask and do the upload process of connecting to the network from another thread (in the doInBackground function).
Related
I want to create an app to upload large images (captured with smartphone so the size is over 3MB) to PHP server and a database with the path of the image. I have followed this tutorial with volley library https://www.simplifiedcoding.net/upload-image-to-server/
But I want to have two different buttons. One for selecting an image and another for uploading it. I know that I'm doing something wrong. Bcause it gives me null bitmap. I don't know what I have to change.
Edit: MainActivity.java
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.Settings;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Base64;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
//ImageView to display image selected
ImageView imageView;
String filePath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//initializing views
imageView = (ImageView) findViewById(R.id.imageView);
//checking the permission
//if the permission is not given we will open setting to add permission
//else app will not open
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && ContextCompat.checkSelfPermission(this,
Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
Uri.parse("package:" + getPackageName()));
finish();
startActivity(intent);
return;
}
//adding click listener to button
findViewById(R.id.buttonChooseImage).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//if everything is ok we will open image chooser
Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, 100);
}
});
findViewById(R.id.buttonUploadImage).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//calling the method uploadBitmap to upload image
uploadBitmap(filePath);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 100 && resultCode == RESULT_OK && data != null) {
//getting the image Uri
Uri imageUri = data.getData();
filePath = getPath(imageUri);
//displaying selected image to imageview
imageView.setImageURI(imageUri);
}
}
// Get Path of selected image
private String getPath(Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
CursorLoader loader = new CursorLoader(getApplicationContext(), contentUri, proj, null, null, null);
Cursor cursor = loader.loadInBackground();
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String result = cursor.getString(column_index);
cursor.close();
return result;
}
private void uploadBitmap(final String imagePath) {
//our custom volley request
VolleyMultipartRequest volleyMultipartRequest = new VolleyMultipartRequest(Request.Method.POST, EndPoints.UPLOAD_URL,
new Response.Listener<NetworkResponse>() {
#Override
public void onResponse(NetworkResponse response) {
try {
JSONObject obj = new JSONObject(new String(response.data));
Toast.makeText(getApplicationContext(), obj.getString("message"), Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
}) {
/*
* Here we are passing image by renaming it with a unique name
* */
#Override
protected Map<String, String> getParams() {
//Converting Bitmap to String
String image = getFileDataFromDrawable(bitmap);
Map<String, String> params = new HashMap<>();
params.put("pic", imagePath);
return params;
}
};
//adding the request to volley
Volley.newRequestQueue(this).add(volleyMultipartRequest);
}
}
May be because in php the max size u can send is 2Mg, try te send a picture less then 2M , if it's work you have to go to php.ini and thange the max_size
i use this code for uploading files and i've not faced problems for uploading files over 14MB.
HttpURLConnection conn = null;
DataOutputStream dos = null;
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024;
final File sourceFile = file_to_upload;
String serverResponseMessage;
String response = null;
if (!sourceFile.isFile()) {
return "no file";
} else {
try {
FileInputStream fileInputStream =
new FileInputStream(sourceFile.getPath());
URL url = "upload_URL";
conn = (HttpURLConnection) url.openConnection();
int size = (int) sourceFile.length();
conn.setFixedLengthStreamingMode(size);
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);
dos = new DataOutputStream(conn.getOutputStream());
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
bytesRead = 0;
long total_bytes = 0;
Log.e("start", "" + size);
do {
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
dos.write(buffer, 0, bufferSize);
total_bytes += bytesRead;
float f1 = total_bytes;
float f2 = size;
float f3 = f1 / f2;
publishProgress(f3);
} while (bytesRead > 0);
int serverResponseCode = conn.getResponseCode();
serverResponseMessage = conn.getResponseMessage();
response = "HTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode;
fileInputStream.close();
dos.flush();
dos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (MalformedURLException ex) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
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'];
}
?>
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?
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" />
I want to write an android app that can upload a file to a c sharp base web server.
So far I have no luck. I kept getting Address family not supported by protocol.
I've added INTERNET and WRITE_EXTERNAL_STORAGE in my manifest file.
Keep in mind that I run this in emulator.
Any idea or suggestion is really appreciated.
Thank you in advance
Justin The
anyway here is my code
Android - Uploader.java
package com.main;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.TextView;
public class Uploader extends AsyncTask<Object, String, Object>
{
URL connectURL;
String params;
String responseString;
String fileName;
byte[] dataToServer;
FileInputStream fileInputStream;
TextView info;
private static final String TAG = "Uploader";
void setUrlAndFile(String urlString, String fileName, TextView info)
{
Log.d(TAG,"StartUploader");
this.info = info;
try
{
fileInputStream = new FileInputStream(fileName);
connectURL = new URL(urlString);
}
catch(Exception e)
{
publishProgress(e.toString());
}
this.fileName = fileName;
}
synchronized void doUpload()
{
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
Log.d(TAG,"lv1");
try
{
Log.d(TAG,"doUpload");
publishProgress("Uploading...");
HttpURLConnection conn = (HttpURLConnection)connectURL.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);
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition:form-data; name=\"uploadedfile\";filename=\"" + fileName + "\"" + lineEnd);
dos.writeBytes(lineEnd);
Log.d(TAG,"LvA");
Log.d(TAG,twoHyphens + boundary + lineEnd + ";Content-Disposition:form-data; name=\"uploadedfile\";filename=\"" + fileName + "\"" + lineEnd);
int bytesAvailable = fileInputStream.available();
int maxBufferSize = 1024;
int bufferSize = Math.min(bytesAvailable, maxBufferSize);
byte[] buffer = new byte[bufferSize];
int bytesRead = fileInputStream.read(buffer,0, bufferSize);
Log.d(TAG,"LvB");
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);
fileInputStream.close();
dos.flush();
InputStream is = conn.getInputStream();
int ch;
Log.d(TAG,"LvC");
StringBuffer buff = new StringBuffer();
while((ch=is.read()) != -1)
{
buff.append((char)ch);
}
publishProgress(buff.toString());
dos.close();
Log.d(TAG,"lv2");
}
catch(Exception e)
{
publishProgress(e.toString());
}
}
#Override
protected Object doInBackground(Object... arg0)
{
Log.d(TAG,"lv1a");
doUpload();
Log.d(TAG,"lv1b");
return null;
}
protected void onProgressUpdate(String... progress)
{
this.info.setText(progress[0]);
}
}
and this is the main activity
package com.main;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FilePermission;
import java.io.OutputStreamWriter;
import java.net.SocketException;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;
public class ReadWriteToPCActivity extends Activity
{
private static final String TAG = "ReadWriteToPCActivity";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
View upload = findViewById(R.id.Upload);
final EditText path = (EditText)findViewById(R.id.Path);
final TextView info = (TextView)findViewById(R.id.Info);
Log.d(TAG,"Start");
File fn = new File(Environment.getExternalStorageDirectory()+"/new.xml");
upload.setOnClickListener
(
new OnClickListener()
{
public void onClick(View v)
{
try
{
Log.d(TAG,"Step1");
WriteFile();
Uploader uploader = new Uploader();
//uploader.setUrlAndFile("http://192.168.0.123/receiver.aspx", path.getText().toString(), info);
uploader.setUrlAndFile("http://192.168.0.123/personalfinance/receiver.aspx", Environment.getExternalStorageDirectory()+"/samplefile.txt", info);
//uploader.setUrlAndFile("http://10.0.2.2/personalfinance/receiver.aspx", Environment.getExternalStorageDirectory()+"/new.xml", info);
//uploader.setUrlAndFile("http://192.168.0.123/personalfinance/ReceiveUpload.aspx", Environment.getExternalStorageDirectory()+"/new.xml", info);
Log.d(TAG,"Upload." + Environment.getExternalStorageDirectory()+"/samplefile.txt;" + info.getText().toString());
uploader.execute();
}
catch(Exception e)
{
path.setText(e.toString());
Log.d(TAG,e.toString());
}
}
private void WriteFile()
{
try
{
Log.d(TAG,"Step 1 write file");
File newfile = new File(Environment.getExternalStorageDirectory() + "/samplefile.txt");
Log.d(TAG,"Step 2 write file");
if(!newfile.exists() && !newfile.createNewFile())
{
Log.d(TAG,"File exists");
}
Log.d(TAG,"cp3");
newfile.createNewFile();
Log.d(TAG,"Step 3 write file");
FileOutputStream fos = null;
Log.d(TAG,"Step 4 write file");
fos = new FileOutputStream(newfile);
Log.d(TAG,"Step 5 write file");
OutputStreamWriter osw = new OutputStreamWriter(fos);
osw.write("Hello Android");
osw.flush();
osw.close();
FilePermission fp;
fp = new FilePermission(Environment.getExternalStorageDirectory()+"/samplefile.txt","read");
Log.d(TAG,"File created");
}
catch(Exception e)
{
Log.d(TAG,e.toString());
}
}
}
);
}
}
and last, this is my receiver file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace PersonalFinance
{
public partial class receiver : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
HttpFileCollection uploadFiles = Request.Files;
HttpPostedFile postedFile = uploadFiles[0];
System.IO.Stream inStream = postedFile.InputStream;
byte[] fileData = new byte[postedFile.ContentLength];
inStream.Read(fileData, 0, postedFile.ContentLength);
postedFile.SaveAs(Server.MapPath("Data") + "\\" + postedFile.FileName);
}
}
}