在过去的几个星期里,我一直在使用一个 Android 应用程序来获取一张要发布到 PHP 服务器的图像。我成功地让它工作了,我能够在图像上点击“共享”,它会将它上传到服务器。
我已经向几个人展示了大约 3 天,但今天它突然停止了工作。现在,当我点击“分享”时,它只显示“错误 website.com”,并且文件没有上传。
我没有更改任何代码(我没有从 Eclipse 重新上传任何新代码,也没有在服务器上编辑 PHP 文件),而且似乎这个错误突然出现。由于它只是说“ERROR website.com”,它的描述性不是很好,但我可以假设该网站是问题所在。所以我检查了 .php 文件,它仍然按预期工作,网站没有崩溃。
有没有人经历过类似的事情,或者有人知道我在哪里可以找到答案吗?
安卓代码:
public class UploadImage extends Activity {
InputStream inputStream;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.activity_starting_point);
Intent intent = getIntent();
Bundle extras = intent.getExtras();
String action = intent.getAction();
// if this is from the share menu
if (Intent.ACTION_SEND.equals(action)) {
if (extras.containsKey(Intent.EXTRA_STREAM)) {
try {
// Get resource path from intent callee
Uri uri = (Uri) extras.getParcelable(Intent.EXTRA_STREAM);
// Query gallery for camera picture via
// Android ContentResolver interface
ContentResolver cr = getContentResolver();
InputStream is = cr.openInputStream(uri);
// Get binary bytes for encode
byte[] data = getBytesFromFile(is);
// base 64 encode for text transmission (HTTP)
int flags = 1;
byte[] encoded_data = Base64.encode(data, flags);
String image_str = new String(encoded_data); // convert to
// string
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("image",
image_str));
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"http://xxxx.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
String the_string_response = convertResponseToString(response);
Toast.makeText(UploadImage.this,
"Response " + the_string_response,
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(UploadImage.this, "ERROR " + e.getMessage(),
Toast.LENGTH_LONG).show();
System.out.println("Error in http connection "
+ e.toString());
}
}
}
}
PHP代码:
<?php
if($base=$_REQUEST['image']){
$binary=base64_decode($base);
header('Content-Type: bitmap; charset=utf-8');
$destination = time() + rand(1, 1000) . ".jpg";
$url_destination = "project_images/" . $destination;
$file = fopen($url_destination, 'wb');
fwrite($file, $binary);
fclose($file);
echo 'Image upload complete.';
?>