当我尝试将图片从手机上传到 php 文件并将其发送到我的计算机时,出现空错误。该文件未到达计算机。当我上传它显示的图片时,该应用程序可以工作,但是当我尝试将其发送到我的计算机时,它会发送空错误。
这行代码给出了错误。
HttpResponse response = httpclient.execute(httppost);
有任何想法吗?谢谢!我的 java 类在下面,我的 php 文件在下面。
package test.example;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap.CompressFormat;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
public class ImageGalleryDemoActivity extends Activity {
InputStream inputStream;
private static int RESULT_LOAD_IMAGE = 1;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);
Button buttonLoadImage = (Button) findViewById(R.id.buttonLoadPicture);
buttonLoadImage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
});
}
@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 = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
ImageView imageView = (ImageView) findViewById(R.id.imgView);
// imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
Bitmap bitmap;
try {
bitmap = BitmapFactory.decodeFile(picturePath);
imageView.setImageBitmap(bitmap);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 90, stream); // compress
// to which
// format
// you want.
int bytes = bitmap.getWidth()*bitmap.getHeight()*4; //calculate how many bytes our image consists of. Use a different value than 4 if you don't use 32bit images.
ByteBuffer byteBuffer = ByteBuffer.allocate(bytes);
bitmap.copyPixelsToBuffer(byteBuffer);
byte[] byte_arr = byteBuffer.array();//stream.toByteArray();
String image_str = Base64.encodeBytes(byte_arr);
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("image", image_str));
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"http://192.168.1.4/Upload_image_ANDROID/upload_image.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
String the_string_response =
convertResponseToString(response);
Toast.makeText(ImageGalleryDemoActivity.this,
"Response " + the_string_response, Toast.LENGTH_LONG)
.show();
} catch (Exception e) {
Toast.makeText(ImageGalleryDemoActivity.this,
"ERROR " + e.getMessage(), Toast.LENGTH_LONG)
.show();
System.out.println("Error in http connection "
+ e.getClass().getName() + " " + e.toString());
}
} catch (Exception e) {
Toast.makeText(
ImageGalleryDemoActivity.this,
"ERROR " + e.getClass().getName() + " "
+ e.getMessage(), Toast.LENGTH_LONG).show();
System.out.println("Error in http connection " + e.toString());
}
}
}
public String convertResponseToString(HttpResponse response)
throws IllegalStateException, IOException {
String res = "";
StringBuffer buffer = new StringBuffer();
inputStream = response.getEntity().getContent();
int contentLength = (int) response.getEntity().getContentLength(); // getting
// content
// length…..
Toast.makeText(ImageGalleryDemoActivity.this,
"contentLength : " + contentLength, Toast.LENGTH_LONG).show();
if (contentLength < 0) {
} else {
byte[] data = new byte[512];
int len = 0;
try {
while (-1 != (len = inputStream.read(data))) {
buffer.append(new String(data, 0, len)); // converting to
// string and
// appending to
// stringbuffer…..
}
} catch (IOException e) {
e.printStackTrace();
}
try {
inputStream.close(); // closing the stream…..
} catch (IOException e) {
e.printStackTrace();
}
res = buffer.toString(); // converting stringbuffer to string…..
Toast.makeText(ImageGalleryDemoActivity.this, "Result : " + res,
Toast.LENGTH_LONG).show();
// System.out.println("Response => " +
// EntityUtils.toString(response.getEntity()));
}
return res;
}
}
上传图片.php
<?php
$base=$_REQUEST['image'];
$binary=base64_decode($base);
header('Content-Type: bitmap; charset=utf-8');
$file = fopen('uploaded_image.jpg', 'wb');
fwrite($file, $binary);
fclose($file);
echo 'Image upload complete!!, Please check your php file directory……';
?>