我有代码从图库中选择图像并通过PHP将选取的图像上传到远程服务器上。当我点击设备上的上传按钮时,它会显示已成功上传的图片。但在我的服务器上没有任何上传的图像。我在下面发布我的Android-java代码和PHP代码。
Java代码
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.Toast;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
public class ProfileInfo extends Activity {
private Uri mImageCaptureUri;
private ImageView mImageView;
Bitmap photo;
File f;
ProgressDialog prgDialog;
String encodedString;
RequestParams params = new RequestParams();
String imgPath, fileName;
private static final int PICK_FROM_CAMERA = 1;
private static final int CROP_FROM_CAMERA = 2;
private static final int PICK_FROM_FILE = 3;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.profile_info);
prgDialog = new ProgressDialog(this);
// Set Cancelable as False
prgDialog.setCancelable(false);
final String [] items = new String [] {"Take from camera", "Select from gallery"};
ArrayAdapter<String> adapter = new ArrayAdapter<String> (this, android.R.layout.select_dialog_item,items);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select Image");
builder.setAdapter( adapter, new DialogInterface.OnClickListener() {
public void onClick( DialogInterface dialog, int item ) { //pick from camera
if (item == 0) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
mImageCaptureUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(),
"tmp_avatar_" + String.valueOf(System.currentTimeMillis()) + ".jpg"));
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
try {
intent.putExtra("return-data", true);
startActivityForResult(intent, PICK_FROM_CAMERA);
} catch (ActivityNotFoundException e) {
e.printStackTrace();
}
} else { //pick from file
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Complete action using"), PICK_FROM_FILE);
}
}
} );
final AlertDialog dialog = builder.create();
mImageView = (ImageView) findViewById(R.id.profile_pic);
mImageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.show();
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK) return;
switch (requestCode) {
case PICK_FROM_CAMERA:
doCrop();
break;
case PICK_FROM_FILE:
mImageCaptureUri = data.getData();
doCrop();
break;
case CROP_FROM_CAMERA:
Bundle extras = data.getExtras();
if (extras != null) {
photo = extras.getParcelable("data");
mImageView.setImageBitmap(photo);
}
f = new File(mImageCaptureUri.getPath());
if (f.exists()) f.delete();
SaveImage(photo, f.getName());
String root = Environment.getExternalStorageDirectory().toString();
imgPath = root+"/ourway/profiles/"+f.getName()+".jpg";
break;
}
}
private void doCrop() {
final ArrayList<CropOption> cropOptions = new ArrayList<CropOption>();
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setType("image/*");
List<ResolveInfo> list = getPackageManager().queryIntentActivities( intent, 0 );
int size = list.size();
if (size == 0) {
Toast.makeText(this, "Can not find image crop app", Toast.LENGTH_SHORT).show();
return;
} else {
intent.setData(mImageCaptureUri);
intent.putExtra("outputX", 200);
intent.putExtra("outputY", 200);
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("scale", true);
intent.putExtra("return-data", true);
if (size == 1) {
Intent i = new Intent(intent);
ResolveInfo res = list.get(0);
i.setComponent( new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
startActivityForResult(i, CROP_FROM_CAMERA);
} else {
for (ResolveInfo res : list) {
final CropOption co = new CropOption();
co.title = getPackageManager().getApplicationLabel(res.activityInfo.applicationInfo);
co.icon = getPackageManager().getApplicationIcon(res.activityInfo.applicationInfo);
co.appIntent= new Intent(intent);
co.appIntent.setComponent( new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
cropOptions.add(co);
}
CropOptionAdapter adapter = new CropOptionAdapter(getApplicationContext(), cropOptions);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Choose Crop App");
builder.setAdapter( adapter, new DialogInterface.OnClickListener() {
public void onClick( DialogInterface dialog, int item ) {
startActivityForResult( cropOptions.get(item).appIntent, CROP_FROM_CAMERA);
}
});
builder.setOnCancelListener( new DialogInterface.OnCancelListener() {
@Override
public void onCancel( DialogInterface dialog ) {
if (mImageCaptureUri != null ) {
getContentResolver().delete(mImageCaptureUri, null, null );
mImageCaptureUri = null;
}
}
} );
AlertDialog alert = builder.create();
alert.show();
}
}
}
//When Upload button is clicked
public void uploadImage(View v) {
// When Image is selected from Gallery
if (imgPath != null && !imgPath.isEmpty()) {
prgDialog.setMessage("Converting Image to Binary Data");
prgDialog.show();
// Convert image to String using Base64
encodeImagetoString();
// When Image is not selected from Gallery
} else {
Toast.makeText(
getApplicationContext(),
"You must select image from gallery before you try to upload",
Toast.LENGTH_LONG).show();
}
} // End of upload image method
// AsyncTask - To convert Image to String
public void encodeImagetoString() {
new AsyncTask<Void, Void, String>() {
protected void onPreExecute() {
};
@Override
protected String doInBackground(Void... params) {
BitmapFactory.Options options = null;
options = new BitmapFactory.Options();
options.inSampleSize = 3;
photo = BitmapFactory.decodeFile(imgPath,
options);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
// Must compress the Image to reduce image size to make upload easy
photo.compress(Bitmap.CompressFormat.PNG, 50, stream);
byte[] byte_arr = stream.toByteArray();
// Encode Image to String
encodedString = Base64.encodeToString(byte_arr, 0);
return "";
}
@Override
protected void onPostExecute(String msg) {
prgDialog.setMessage("Calling Upload");
// Put converted Image string into Async Http Post param
params.put("image", encodedString);
// Trigger Image upload
triggerImageUpload();
}
}.execute(null, null, null);
}
public void triggerImageUpload() {
makeHTTPCall();
}
// Make Http call to upload Image to Php server
public void makeHTTPCall() {
prgDialog.setMessage("Invoking Php");
AsyncHttpClient client = new AsyncHttpClient();
// Don't forget to change the IP address to your LAN address. Port no as well.
client.post("http://webdesignerways.com/ourway/ImageUpload.php",
params, new AsyncHttpResponseHandler() {
// When the response returned by REST has Http
// response code '200'
@Override
public void onSuccess(String response) {
// Hide Progress Dialog
prgDialog.hide();
Toast.makeText(getApplicationContext(), response,
Toast.LENGTH_LONG).show();
}
// When the response returned by REST has Http
// response code other than '200' such as '404',
// '500' or '403' etc
@Override
public void onFailure(int statusCode, Throwable error,
String content) {
// Hide Progress Dialog
prgDialog.hide();
// When Http response code is '404'
if (statusCode == 404) {
Toast.makeText(getApplicationContext(),
"Requested resource not found",
Toast.LENGTH_LONG).show();
}
// When Http response code is '500'
else if (statusCode == 500) {
Toast.makeText(getApplicationContext(),
"Something went wrong at server end",
Toast.LENGTH_LONG).show();
}
// When Http response code other than 404, 500
else {
Toast.makeText(
getApplicationContext(),
"Error Occured \n Most Common Error: \n1. Device not connected to Internet\n2. Web App is not deployed in App server\n3. App server is not running\n HTTP Status code : "
+ statusCode, Toast.LENGTH_LONG)
.show();
}
}
});
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
// Dismiss the progress bar when application is closed
if (prgDialog != null) {
prgDialog.dismiss();
}
}
private void SaveImage(Bitmap finalBitmap, String name) {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/ourway/profiles");
myDir.mkdirs();
String fname = name +".jpg";
File file = new File (myDir, fname);
if (file.exists ()) file.delete ();
try {
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
} // End of main class
PHP代码
<?php
include_once("config.php");
// Get image string posted from Android App
$base=$_REQUEST['image'];
// Get file name posted from Android App
$filename = $_REQUEST['filename'];
// Decode Image
$binary=base64_decode($base);
header('Content-Type: bitmap; charset=utf-8');
// Images will be saved under 'www/imgupload/uplodedimages' folder
$file = fopen('uploadedimages/'.$filename, 'wb');
// Create File
fwrite($file, $binary);
fclose($file);
echo 'Image upload complete, Please check your php file directory';
?>