我必須做一個Android應用程序,我有一個上傳照片到服務器的問題。我試過一些例子,但不起作用。在Android上通過php將照片上傳到Ubuntu服務器
我的觀點包含一個按鈕,用於從圖庫或照相機中選擇圖像,然後用另一個按鈕,我必須通過php文件上傳到服務器。
我的Android代碼如下:
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數據庫中的路徑。
感謝您的幫助。