android upload large images - android

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

Related

crash my app then running app by emulator (API 23 Android 6.0)

In my app user can upload image by camera or gallery.
app run in nox player(4.4.2) whithout error.
but if I run app by emulator android studio (Nexus 6 API 23 Android 6.0),app When upload image is crashed.
also app Catch permission for use camera and read, write storage from user.
Error in android monitor :
10-03 01:00:46.258 3549-3549/com.google.android.apps.photos E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.google.android.apps.photos, PID: 3549
java.lang.RuntimeException: Unable to resume activity {com.google.android.apps.photos/com.google.android.apps.photos.photoeditor.intents.EditActivity}: java.lang.UnsupportedOperationException: No 'output' extra specified and can not save to specified inputUri: content://com.google.android.apps.photos.contentprovider/-1/1/content%3A%2F%2Fmedia%2Fexternal%2Fimages%2Fmedia%2F37/ACTUAL/1435618852
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3103)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3134)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1388)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.UnsupportedOperationException: No 'output' extra specified and can not save to specified inputUri: content://com.google.android.apps.photos.contentprovider/-1/1/content%3A%2F%2Fmedia%2Fexternal%2Fimages%2Fmedia%2F37/ACTUAL/1435618852
at com.google.android.apps.photos.photoeditor.intents.EditActivity.a(PG:11301)
at ggt.a(PG:87)
at lhy.a(PG:219)
at lhy.O_(PG:189)
at ngn.a(PG:188)
at ngk.a(PG:92)
at ngk.l(PG:184)
at nhi.onResume(PG:64)
at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1258)
at android.app.Activity.performResume(Activity.java:6312)
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3092)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3134) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1388) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5417) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
build.gradle code :
android {
compileSdkVersion 27
buildToolsVersion "27.0.3"
defaultConfig {
applicationId "ir.mosayebtorabi.sapp"
minSdkVersion 17
targetSdkVersion 27
versionCode 1
versionName "1.0"
multiDexEnabled true
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
vectorDrawables.useSupportLibrary = true
}
Activity Code :
package ir.mosayebtorabi.sapp.Register_Pack;
import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Calendar;
import de.hdodenhof.circleimageview.CircleImageView;
import ir.mosayebtorabi.sapp.Global_Class.Global;
import ir.mosayebtorabi.sapp.Global_Class.Request_Permissions;
import ir.mosayebtorabi.sapp.R;
import ir.mosayebtorabi.sapp.Register_Pack.Load_Last_Project.List_Of_Last_Project;
import ir.mosayebtorabi.sapp.Global_Class.Roozh;
public class Get_Info_New_Admin extends AppCompatActivity {
Request_Permissions Request_Permissions;
static Get_Info_New_Admin Get_Info_New_Admin;
Add_New_ProjectControl Add_New_ProjectControl;
Get_Last_CompanyCode Get_Last_CompanyCode;
ir.mosayebtorabi.sapp.Register_Pack.Delete_Pic_From_Server Delete_Pic_From_Server;
CircleImageView fab;
ImageView imageView;
Button buttonCamera, buttonGallery ;
File file;
Uri uri;
Intent CamIntent, GalIntent, CropIntent ;
public static final int RequestPermissionCode = 1 ;
DisplayMetrics displayMetrics ;
int width, height;
ProgressBar progressBar;
ProgressBar prog1;
Button uploadButton;
//upload
int serverResponseCode = 0;
final String uploadFilePath = Environment.getExternalStorageDirectory().getPath() +"/Sapp/.Profile/";
final String uploadFileName = Global.Send_telephone_TelePhone + ".jpg";
String upLoadServerUri = null;
String Picture1="";
private Bitmap bitmap;
//upload
Intent i = new Intent(
Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_get__info__new__admin);
Get_Info_New_Admin = this;
final TextView name=(TextView)findViewById(R.id.name);
final TextView family=(TextView)findViewById(R.id.family);
final TextView companyname=(TextView)findViewById(R.id.companyname);
final TextView projectname=(TextView)findViewById(R.id.projectname);
final Button send=(Button)findViewById(R.id.send);
final Button back=(Button)findViewById(R.id.back);
fab=(CircleImageView)findViewById(R.id.fab);
progressBar =(ProgressBar)findViewById(R.id.progressBar33);
prog1 =(ProgressBar)findViewById(R.id.prog1);
upLoadServerUri = "http://"+ Global.url_connection+"/Sapp/UploadToServer.php";
File file2= new File(android.os.Environment.getExternalStorageDirectory()+ "/Sapp/.Profile/"+
Global.Send_telephone_TelePhone + ".jpg");
if(file2.exists())
{
Bitmap bmp = BitmapFactory.decodeFile(String.valueOf(file2));
fab.setImageBitmap(bmp);
}else{
if (!Global.C0_adapter_ProfilePic.equals("")) {
Glide.with(Get_Info_New_Admin.this).load("http://"+ Global.url_connection+"/Sapp/profile_pic/" +
Global.C0_adapter_ProfilePic).into(fab);
}else{
Glide.with(Get_Info_New_Admin.this).load(R.drawable.blankimageforshoe).into(fab);
}
}
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
}
});
if (!Global.C0_apiservis_Name.equals("")){
name.setText(Global.C0_apiservis_Name);
family.setText(Global.C0_apiservis_Family);
name.setEnabled(false);
family.setEnabled(false);
}
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent aaaaa=new Intent(Get_Info_New_Admin.this,List_Of_Last_Project.class);
Get_Info_New_Admin.this.startActivity(aaaaa);
((Activity) Get_Info_New_Admin.this).finish();
}
});
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String list="";
if (name.getText().toString().equals("")){
name.setError("نام خود را وارد کنید");
name.requestFocus();
list="notok";
}
if (family.getText().toString().equals("") && !list.equals("notok")){
family.setError("نام خانوادگی خود را وارد کنید");
family.requestFocus();
list="notok";
}
if (companyname.getText().toString().equals("") && !list.equals("notok")){
companyname.setError("نام شرکت را وارد کنید");
companyname.requestFocus();
list="notok";
}
if (projectname.getText().toString().equals("") && !list.equals("notok")){
projectname.setError("موضوع فعالیت شرکت را وارد کنید");
projectname.requestFocus();
list="notok";
}
if (!list.equals("notok")){
//get last companycode
name.setEnabled(false);
family.setEnabled(false);
companyname.setEnabled(false);
projectname.setEnabled(false);
prog1.setVisibility(View.VISIBLE);
int CompanyCode11=Integer.parseInt(Global.Get_Last_CompanyCode_CompanyCode)+1;
String CompanyCode1=String.valueOf(CompanyCode11);
String companyname1=companyname.getText().toString();
String projectname1=projectname.getText().toString();
String Designation1="مسئول کنترل پروژه";
String name1=name.getText().toString();
String family1=family.getText().toString();
String TelePhone1=Global.Send_telephone_TelePhone;
String StatueUpLevel1="3";
Roozh jCal = new Roozh();
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int mo = calendar.get(Calendar.MONTH);
mo++;
int da = calendar.get(Calendar.DAY_OF_MONTH);
jCal.GregorianToPersian(year, mo, da);
String Data_Accept1=jCal.toString();
String Staute1="3";
String Access1="3";
String Picture1=Global.Send_telephone_TelePhone+".jpg";
String Invited1=name.getText().toString() + " " + family.getText().toString();
Add_New_ProjectControl=new Add_New_ProjectControl(Get_Info_New_Admin.this);
Add_New_ProjectControl.Add_New_ProjectControl(CompanyCode1,companyname1,projectname1,Designation1,name1,family1
,TelePhone1,StatueUpLevel1,Data_Accept1,Staute1,Access1,Picture1,Invited1,"online");
}
}
});
}
public void selectImage() {
final CharSequence[] options = { "دوربین", "انتخاب عکس از گالری","حذف عکس","انصراف" };
AlertDialog.Builder builder = new AlertDialog.Builder(Get_Info_New_Admin.this);
builder.setTitle("انتخاب تصویر پروفایل");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals("دوربین"))
{
ClickImageFromCamera() ;
}
else if (options[item].equals("انتخاب عکس از گالری"))
{
GetImageFromGallery();
}
else if (options[item].equals("حذف عکس")) {
Drawable myDrawable = getResources().getDrawable(R.drawable.blankimageforshoe);
fab.setImageDrawable(myDrawable);
Picture1="";
Global.Get_Info_New_Admin_SelectImage="";
//deleto from sdcard
File file= new File(android.os.Environment.getExternalStorageDirectory()+ "/Sapp/.Profile/"+
Global.Send_telephone_TelePhone + ".jpg");
if(file.exists())
{
file.delete();
}
//
ProgressBar progressBar33=(ProgressBar)findViewById(R.id.progressBar33);
progressBar33.setVisibility(View.VISIBLE);
Global.What_Page="Get_Info_New_Admin";
Delete_Pic_From_Server=new Delete_Pic_From_Server(Get_Info_New_Admin.this);
Delete_Pic_From_Server.Delete_Pic_From_Server( Global.Send_telephone_TelePhone,Global.Send_telephone_TelePhone + ".jpg");
}
else if (options[item].equals("انصراف")) {
dialog.dismiss();
}
}
});
builder.show();
}
//SAVE IMAGE
private void save() {
FileOutputStream out = null;
Bitmap bitmap = ((BitmapDrawable) fab.getDrawable()).getBitmap();
try {
out = new FileOutputStream(getFilename());
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
new Thread(new Runnable() {
public void run() {
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(Get_Info_New_Admin.this, "در حال بارگزاری", Toast.LENGTH_SHORT).show();
}
});
uploadFile(uploadFilePath + "" + uploadFileName);
}
}).start();
} catch (FileNotFoundException e) {
e.printStackTrace();
Toast.makeText(this, "خطای نامشخص", Toast.LENGTH_SHORT).show();
}
}
private String getFilename() {
File file = new File(Environment.getExternalStorageDirectory()+"/Sapp", ".Profile");
if (!file.exists()) {
file.mkdirs();
}
String uriSting = (file.getAbsolutePath() + "/" + Global.Send_telephone_TelePhone + ".jpg");
return uriSting;
}
//SAVE IMAGE
public void ClickImageFromCamera() {
CamIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
file = new File(Environment.getExternalStorageDirectory(),
"file" + String.valueOf(System.currentTimeMillis()) + ".jpg");
uri = Uri.fromFile(file);
CamIntent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, uri);
CamIntent.putExtra("return-data", true);
startActivityForResult(CamIntent, 0);
}
public void GetImageFromGallery(){
GalIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(Intent.createChooser(GalIntent, "Select Image From Gallery"), 2);
}
public void ImageCropFunction() {
// Image Crop Code
try {
CropIntent = new Intent("com.android.camera.action.CROP");
CropIntent.setDataAndType(uri, "image/*");
CropIntent.putExtra("crop", "true");
CropIntent.putExtra("outputX", 1600);
CropIntent.putExtra("outputY", 1600);
CropIntent.putExtra("aspectX", 10);
CropIntent.putExtra("aspectY", 10);
CropIntent.putExtra("scaleUpIfNeeded", true);
CropIntent.putExtra("return-data", true);
startActivityForResult(CropIntent, 1);
} catch (ActivityNotFoundException e) {
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 0 && resultCode == RESULT_OK) {
ImageCropFunction();
}
else if (requestCode == 2) {
if (data != null) {
uri = data.getData();
ImageCropFunction();
}
}
else if (requestCode == 1) {
if (data != null) {
Bundle bundle = data.getExtras();
try{
Bitmap bitmap = bundle.getParcelable("data");
fab.setImageBitmap(bitmap);
save();
progressBar.setVisibility(View.VISIBLE);
}catch (Exception e){
}
}
}
}
public void onRequestPermissionsResult(int RC, String per[], int[] PResult) {
switch (RC) {
case RequestPermissionCode:
if (PResult.length > 0 && PResult[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(Get_Info_New_Admin.this,"Permission Granted, Now your application can access CAMERA.", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(Get_Info_New_Admin.this,"Permission Canceled, Now your application cannot access CAMERA.", Toast.LENGTH_LONG).show();
}
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 =30000 * 30000;
File sourceFile = new File(sourceFileUri);
if (!sourceFile.isFile()) {
Log.e("uploadFile", "Source File not exist :"
+uploadFilePath + "" + uploadFileName);
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(Get_Info_New_Admin.this, "خطای دستیابی به فابل", Toast.LENGTH_SHORT).show();
}
});
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() {
Toast.makeText(Get_Info_New_Admin.this, "آپلود فایل کامل شد.", Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.INVISIBLE);
}
});
}
//close the streams //
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
ex.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(Get_Info_New_Admin.this, "اتصال برقرار نشد.", Toast.LENGTH_SHORT).show();
}
});
Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
} catch (Exception e) {
e.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(Get_Info_New_Admin.this, "خطا.مجددا امتحان کنید.", Toast.LENGTH_SHORT).show();
}
});
}
return serverResponseCode;
} // End else block
}
public static Get_Info_New_Admin getInstance(){
return Get_Info_New_Admin;
}
}
PHP Code (UploadToServer):
<?php
$file_path = "profile_pic/";
$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";
}
?>
No 'output' extra specified and can not save to specified inputUri
In your EditActivity, where you are using URI to save(or whatever), you didn't specify the output path, that's why you get the error.
For example, add a second paramater as the output path and then it will work.

error when i choose image from gallery using device but not if using emulator

why when i choose image from gallery using my device getting error but if using emulator not?
note * the emulator using api 17, and my device using api 19
and after i get error i tried remove this part code from WC_Activity.java and it's working normally
how i can fix that?
if (Build.VERSION.SDK_INT < 11)
realPath = RealPathUtil.getRealPathFromURI_BelowAPI11(this, data.getData());
// SDK >= 11 && SDK < 19
else if (Build.VERSION.SDK_INT < 19)
realPath = RealPathUtil.getRealPathFromURI_API11to18(this, data.getData());
// SDK > 19 (Android 4.4)
else
realPath = RealPathUtil.getRealPathFromURI_API19(this, data.getData());
full code
WC_Activity.java
package com.emergency.e_place;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.ByteArrayOutputStream;
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;
/**
* Created by Eggy on 5/3/2016.
*/
public class WC_Activity extends AppCompatActivity {
final String TAG = "DEBUG";
private ImageSwitcher imageview;
private int PICK_IMAGE_REQUEST = 1;
private int ACTION_IMAGE_CAPTURE=1;
Button b;
Button Camera;
int serverResponseCode = 0;
ProgressDialog dialog = null;
String realPath;
String Latitude;
String Longitude;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_wc);
b = (Button) findViewById(R.id.btnSimpanWC);
Camera = (Button) findViewById(R.id.Camera);
Toolbar toolbar=(Toolbar)findViewById(R.id.toolbarWC);
setSupportActionBar(toolbar);
//ambil lokasi dari MainActivity
Intent myIntent = getIntent(); // gets the previously created intent
Latitude = myIntent.getStringExtra("Latitude"); // will return "FirstKeyValue"
Longitude= myIntent.getStringExtra("Longitude"); // will return "SecondKeyValue"
Log.d(TAG, "onLocationChanged: " + Longitude);
//ambil lokasi dari MainActivity
Button ChooseFile = (Button) findViewById(R.id.ChooseFile);
ChooseFile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
// Show only images, no videos or anything else
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
// Always show the chooser (if there are multiple options available)
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}
});
Button Camera = (Button) findViewById(R.id.Camera);
Camera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent,ACTION_IMAGE_CAPTURE);
}
});
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog = ProgressDialog.show(WC_Activity.this, "", "Uploading file...", true);
new Thread(new Runnable() {
public void run() {
runOnUiThread(new Runnable() {
public void run() {
}
});
int response= uploadFile(realPath);
System.out.println("RES : " + response);
}
}).start();
}
});
}
public int uploadFile(String sourceFileUri) {
String upLoadServerUri = "http://192.168.1.101/e_place/android/upload_image_wc.php";
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()) {
Log.e("uploadFile", "Source File Does not exist");
return 0;
}
try { // open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL url = new URL(upLoadServerUri);
conn = (HttpURLConnection) url.openConnection(); // Open a HTTP connection to the URL
conn.setDoInput(true); // Allow Inputs
conn.setDoOutput(true); // Allow Outputs
conn.setUseCaches(false); // Don't use a Cached Copy
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
//ubah nama gambar menjadi data dari latitude_longitude
String namafoto = "/"+Latitude+"_"+Longitude+".";
String namafile = fileName.substring(0,fileName.lastIndexOf("/")) +namafoto+(fileName.substring(fileName.lastIndexOf(".")+1));
conn.setRequestProperty("uploaded_file", namafile);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""+ namafile + "\"" + lineEnd);
dos.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available(); // create a buffer of maximum size
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
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() {
Toast.makeText(WC_Activity.this, "File Upload Complete.", Toast.LENGTH_SHORT).show();
}
});
}
//close the streams //
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
dialog.dismiss();
ex.printStackTrace();
Toast.makeText(WC_Activity.this, "MalformedURLException", Toast.LENGTH_SHORT).show();
Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
} catch (Exception e) {
dialog.dismiss();
e.printStackTrace();
Toast.makeText(WC_Activity.this, "Exception : " + e.getMessage(), Toast.LENGTH_SHORT).show();
Log.e("Upload file to server Exception", "Exception : " + e.getMessage(), e);
}
dialog.dismiss();
return serverResponseCode;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
ImageView imageView = (ImageView) findViewById(R.id.imageView);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri uri = data.getData();
if (Build.VERSION.SDK_INT < 11)
realPath = RealPathUtil.getRealPathFromURI_BelowAPI11(this, data.getData());
// SDK >= 11 && SDK < 19
else if (Build.VERSION.SDK_INT < 19)
realPath = RealPathUtil.getRealPathFromURI_API11to18(this, data.getData());
// SDK > 19 (Android 4.4)
else
realPath = RealPathUtil.getRealPathFromURI_API19(this, data.getData());
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
Log.d(TAG, "niiih : " + realPath);
imageView.setImageBitmap(bitmap);
imageView.getLayoutParams().height = 300;
imageView.getLayoutParams().width = 300;
} catch (IOException e) {
e.printStackTrace();
}
}
}
public Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
}
public String getRealPathFromURI(Uri uri) {
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
return cursor.getString(idx);
}
}
RealPathUtil.java
package com.emergency.e_place;
/**
* Created by Eggy on 6/6/2016.
*/
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.CursorLoader;
import android.database.Cursor;
import android.net.Uri;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
public class RealPathUtil {
#SuppressLint("NewApi")
public static String getRealPathFromURI_API19(Context context, Uri uri){
String filePath = "";
String wholeID = DocumentsContract.getDocumentId(uri);
// Split at colon, use second item in the array
String id = wholeID.split(":")[1];
String[] column = { MediaStore.Images.Media.DATA };
// where id is equal to
String sel = MediaStore.Images.Media._ID + "=?";
Cursor cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
column, sel, new String[]{ id }, null);
int columnIndex = cursor.getColumnIndex(column[0]);
if (cursor.moveToFirst()) {
filePath = cursor.getString(columnIndex);
}
cursor.close();
return filePath;
}
#SuppressLint("NewApi")
public static String getRealPathFromURI_API11to18(Context context, Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
String result = null;
CursorLoader cursorLoader = new CursorLoader(
context,
contentUri, proj, null, null, null);
Cursor cursor = cursorLoader.loadInBackground();
if(cursor != null){
int column_index =
cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
result = cursor.getString(column_index);
}
return result;
}
public static String getRealPathFromURI_BelowAPI11(Context context, Uri contentUri){
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index
= cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
}
logcat
06-07 18:37:54.324 5168-5168/com.emergency.e_place E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.emergency.e_place, PID: 5168
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { dat=content://media/external/images/media/12513 (has extras) }} to activity {com.emergency.e_place/com.emergency.e_place.WC_Activity}: java.lang.NullPointerException
at android.app.ActivityThread.deliverResults(ActivityThread.java:3601)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3644)
at android.app.ActivityThread.access$1400(ActivityThread.java:166)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1329)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5511)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.emergency.e_place.WC_Activity.getImageUri(WC_Activity.java:244)
at com.emergency.e_place.WC_Activity.onActivityResult(WC_Activity.java:209)
at android.app.Activity.dispatchActivityResult(Activity.java:5514)
at android.app.ActivityThread.deliverResults(ActivityThread.java:3597)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3644) 
at android.app.ActivityThread.access$1400(ActivityThread.java:166) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1329) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:146) 
at android.app.ActivityThread.main(ActivityThread.java:5511) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:515) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099) 
at dalvik.system.NativeStart.main(Native Method) 
[ 06-07 18:37:54.334 212: 362 D/ ]
RIL_onMultiClientUnsolicitedResponse:
[ 06-07 18:37:54.334 212: 362 E/ ]
unsupported multiclient unsolicited response code 1009
Try to use Intent.ACTION_PICK instead of Intent.ACTION_GET_CONTENT to pick a photo from the gallery.

How to post data using multipart?

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

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" />

Error Upload Image to Server

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).

Categories

Resources