【发布时间】:2014-02-14 00:53:33
【问题描述】:
我必须做一个 Android 应用程序,我在将照片上传到服务器时遇到问题。我已经尝试了一些示例,但不起作用。
我的视图包含一个用于从图库或相机中选择图像的按钮,然后我必须使用另一个按钮通过 php 文件上传到服务器。
我的安卓代码如下:
class ImageGalleryTask extends AsyncTask<Void, Void, String> {
protected String doInBackground(Void... unsued) {
InputStream is;
BitmapFactory.Options bfo;
Bitmap bitmapOrg;
ByteArrayOutputStream bao ;
bfo = new BitmapFactory.Options();
bfo.inSampleSize = 2;
//bitmapOrg = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory() + "/" + customImage, bfo);
bao = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, bao);
byte [] ba = bao.toByteArray();
String ba1 = Base64.encodeBytes(ba);
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("fotoUp",ba1));
nameValuePairs.add(new BasicNameValuePair("name","image_android"));
Log.v("log_tag", System.currentTimeMillis()+".jpg");
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new
// Here you need to put your server file address
HttpPost("http://xxx.xxx.xxx.xxxx/xxxxxxxxxxxx/upload_photo.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.v("log_tag", "Success" );
}catch(Exception e){
Log.v("log_tag", "Error in http connection "+e.toString());
}
return "Success";
// (null);
}
@Override
protected void onProgressUpdate(Void... unsued) {
}
@Override
protected void onPostExecute(String sResponse) {
try {
if (dialog.isShowing())
dialog.dismiss();
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
e.getMessage(),
Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
}
}
}
而php是:
$ruta = "photos/" . basename( $_FILES['fotoUp']['name']);
if(move_uploaded_file($_FILES['fotoUp']['tmp_name'], $ruta))
chmod ("uploads/".basename( $_FILES['fotoUp']['name']), 0644);
应用程序工作,但图像不上传到服务器。我将 Ubuntu 服务器中的权限更改为 777。
我可以上传照片的 Ubuntu 服务器文件夹位于 var/www/xxxx/photos 中,而 php 文件位于 var/www/xxx/upload_photo.php 中
我也知道如何保存存储在 mySQL 数据库中的路径。
感谢您的帮助。
【问题讨论】: