我正在开发一个Android应用程序,它可以将图片发送到远程服务器,但是我得到了错误。
错误是,
11-24 13:25:30.848: E/org.json.JSONException(2386): Value <br of type java.lang.String cannot be converted to JSONObject
11-24 13:25:30.848: E/org.json.JSONException(2386): org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
11-24 13:25:30.848: E/org.json.JSONException(2386): at org.json.JSON.typeMismatch(JSON.java:107)
11-24 13:25:30.848: E/org.json.JSONException(2386): at org.json.JSONObject.<init>(JSONObject.java:158)
11-24 13:25:30.848: E/org.json.JSONException(2386): at org.json.JSONObject.<init>(JSONObject.java:171)
11-24 13:25:30.848: E/org.json.JSONException(2386): at com.isummation.imageupload.ImageUpload$ImageUploadTask.onPostExecute(ImageUpload.java:201)
11-24 13:25:30.848: E/org.json.JSONException(2386): at com.isummation.imageupload.ImageUpload$ImageUploadTask.onPostExecute(ImageUpload.java:1)
11-24 13:25:30.848: E/org.json.JSONException(2386): at android.os.AsyncTask.finish(AsyncTask.java:417)
11-24 13:25:30.848: E/org.json.JSONException(2386): at android.os.AsyncTask.access$300(AsyncTask.java:127)
11-24 13:25:30.848: E/org.json.JSONException(2386): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:429)
11-24 13:25:30.848: E/org.json.JSONException(2386): at android.os.Handler.dispatchMessage(Handler.java:99)
11-24 13:25:30.848: E/org.json.JSONException(2386): at android.os.Looper.loop(Looper.java:150)
11-24 13:25:30.848: E/org.json.JSONException(2386): at android.app.ActivityThread.main(ActivityThread.java:4263)
11-24 13:25:30.848: E/org.json.JSONException(2386): at java.lang.reflect.Method.invokeNative(Native Method)
11-24 13:25:30.848: E/org.json.JSONException(2386): at java.lang.reflect.Method.invoke(Method.java:507)
11-24 13:25:30.848: E/org.json.JSONException(2386): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
11-24 13:25:30.848: E/org.json.JSONException(2386): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
11-24 13:25:30.848: E/org.json.JSONException(2386): at dalvik.system.NativeStart.main(Native Method)
我的代码是,
public class ImageUpload extends Activity {
private static final int PICK_IMAGE = 1;
private ImageView imgView;
private Button upload;
private EditText caption;
private Bitmap bitmap;
private ProgressDialog dialog;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.imageupload);
imgView = (ImageView) findViewById(R.id.ImageView);
upload = (Button) findViewById(R.id.Upload);
caption = (EditText) findViewById(R.id.Caption);
upload.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (bitmap == null) {
Toast.makeText(getApplicationContext(),
"Please select image", Toast.LENGTH_SHORT).show();
} else {
dialog = ProgressDialog.show(ImageUpload.this, "Uploading",
"Please wait...", true);
new ImageUploadTask().execute();
}
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.imageupload_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.ic_menu_gallery:
try {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(
Intent.createChooser(intent, "Select Picture"),
PICK_IMAGE);
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
e.getMessage(),
Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case PICK_IMAGE:
if (resultCode == Activity.RESULT_OK) {
Uri selectedImageUri = data.getData();
String filePath = null;
try {
// OI FILE Manager
String filemanagerstring = selectedImageUri.getPath();
// MEDIA GALLERY
String selectedImagePath = getPath(selectedImageUri);
if (selectedImagePath != null) {
filePath = selectedImagePath;
} else if (filemanagerstring != null) {
filePath = filemanagerstring;
} else {
Toast.makeText(getApplicationContext(), "Unknown path",
Toast.LENGTH_LONG).show();
Log.e("Bitmap", "Unknown path");
}
if (filePath != null) {
decodeFile(filePath);
} else {
bitmap = null;
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Internal error",
Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
}
}
break;
default:
}
}
class ImageUploadTask extends AsyncTask<Void, Void, String> {
@Override
protected String doInBackground(Void... unsued) {
try {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost("http://192.168.1.101/kyaloManager/uploadimage.php");
MultipartEntity entity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 100, bos);
byte[] data = bos.toByteArray();
entity.addPart("file", new ByteArrayBody(data, "image.JPEG"));
entity.addPart("photoCaption", new StringBody(caption.getText()
.toString()));
httpPost.setEntity( entity);
HttpResponse response = httpClient.execute(httpPost,
localContext);
BufferedReader reader = new BufferedReader(
new InputStreamReader(
response.getEntity().getContent(), "UTF-8"));
String sResponse = reader.readLine();
return sResponse;
} catch (Exception e) {
if (dialog.isShowing())
dialog.dismiss();
Toast.makeText(getApplicationContext(),
e.getMessage(),
Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
return null;
}
// (null);
}
@Override
protected void onProgressUpdate(Void... unsued) {
}
@Override
protected void onPostExecute(String sResponse) {
try {
if (dialog.isShowing())
dialog.dismiss();
if (sResponse != null) {
JSONObject JResponse = new JSONObject(sResponse);
int success = JResponse.getInt("SUCCESS");
String message = JResponse.getString("MESSAGE");
if (success == 0) {
Toast.makeText(getApplicationContext(), message,
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),
"Photo uploaded successfully",
Toast.LENGTH_SHORT).show();
caption.setText("");
}
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
e.getMessage(),
Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
}
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
if (cursor != null) {
// HERE YOU WILL GET A NULLPOINTER IF CURSOR IS NULL
// THIS CAN BE, IF YOU USED OI FILE MANAGER FOR PICKING THE MEDIA
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} else
return null;
}
public void decodeFile(String filePath) {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, o);
// The new size we want to scale to
final int REQUIRED_SIZE = 1024;
// Find the correct scale value. It should be the power of 2.
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
bitmap = BitmapFactory.decodeFile(filePath, o2);
imgView.setImageBitmap(bitmap);
}
}
php代码是,
$target_path1 = "images/uploads/";
$target_path1 = $target_path1 . basename( $_FILES['uploaded_file']['name']);
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $target_path1)) {
echo "The first file ". basename( $_FILES['uploaded_file']['name']).
" has been uploaded.";
} else{
echo "There was an error uploading the file, please try again!";
echo "filename: " . basename( $_FILES['uploaded_file']['name']);
echo "target_path: " .$target_path1;
}
上述代码有什么问题?
答案 0 :(得分:0)
要存储图像,您可以通过添加以下行将其转换为base64格式:
String strData = Base64.encodeToString(data, Base64.DEFAULT);
entity.addPart("file", strData);
对于PHP方面,您可以执行以下操作:
$fp = fopen( $output_file, "wb" );
fwrite( $fp, base64_decode( $strData) );
fclose( $fp );
其中$ strData是base64编码的字符串