Android-将照片上传到服务器

Android-将照片上传到服务器

问题描述:

the 上传产品类别在我的数据库中注册一个产品,并将照片上传到我的服务器。 我想将文件上传到我的服务器。 当我执行我的应用程序完美的工作,该产品是在数据库中注册,但在我的服务器,照片尚未加载。Android-将照片上传到服务器

当我调试,我把一个断点httppost.setEntity(mpEntity);file属性附加伤害值是/storage/emulated/0/aaaa/20150529_104715.jpg

哪里保存我的文件的路径为http://aaaa.com/app/imagenes/和的upload.php路径是http://aaaa.com/app

这里我的代码:

atributes:

private List<NameValuePair> params = new ArrayList<NameValuePair>(1); 
private File file; 
private String imageFileName = ""; 
private String urlImag ="http://aaaa.com/app/imagenes/"; 
private EditText etNombreProducto,etDescripcion,etPrecioDia,etPrecioSemana; 
private Bitmap bitmap=null; 

方法:

public void takePhoto() { 



     String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); 
     imageFileName = timeStamp + ".jpg"; 


     //Creamos el Intent para llamar a la Camara 
     Intent cameraIntent = new Intent(
       android.provider.MediaStore.ACTION_IMAGE_CAPTURE); 
     //Creamos una carpeta en la memeria del terminal 
     File imagesFolder = new File(
       Environment.getExternalStorageDirectory(), "aaaa"); 
     imagesFolder.mkdirs(); 
     //anadimos el nombre de la imagen 
     file= new File(imagesFolder, imageFileName); 
     Uri uriSavedImage = Uri.fromFile(file); 
     //Le decimos al Intent que queremos grabar la imagen 
     cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage); 
     //Lanzamos la aplicacion de la camara con retorno (forResult) 
     startActivityForResult(cameraIntent, 1); 


    } 

    protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
     //Comprovamos que la foto se a realizado 
     if (requestCode == 1 && resultCode == RESULT_OK) { 
      //Creamos un bitmap con la imagen recientemente 
      //almacenada en la memoria 
      bitmap= BitmapFactory.decodeFile(
        Environment.getExternalStorageDirectory() + 
          "/aaaa/" + imageFileName); 
//   //Anadimos el bitmap al imageView para 
//   //mostrarlo por pantalla 
//   img.setImageBitmap(bMap); 
     } 
    } 


    private boolean uploadFoto(String imag){ 
     HttpClient httpclient = new DefaultHttpClient(); 
     httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); 
     HttpPost httppost = new HttpPost("http://aaaa.com/app/upload.php"); 
     MultipartEntity mpEntity = new MultipartEntity(); 

     ContentBody contentBody = new FileBody(file,"image/jpeg"); 
     mpEntity.addPart("foto", contentBody); 
     httppost.setEntity(mpEntity); 
     try { 
      httpclient.execute(httppost); 
      httpclient.getConnectionManager().shutdown(); 
      return true; 
     } catch (ClientProtocolException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
     return false; 
    } 
    private boolean onInsert(){ 
     String nombreP = etNombreProducto.getText().toString(); 
     String descripcion = etDescripcion.getText().toString(); 
     String precioD = etPrecioDia.getText().toString(); 
     String precioS=etPrecioSemana.getText().toString(); 
     HttpClient httpclient; 

     params.add(new BasicNameValuePair("nombre", nombreP)); 
     params.add(new BasicNameValuePair("descripcion", descripcion)); 
     params.add(new BasicNameValuePair("preciodia", precioD)); 
     params.add(new BasicNameValuePair("preciosemana", precioS)); 
     params.add(new BasicNameValuePair("imagen", urlImag + imageFileName)); 
     HttpPost httppost; 
     httpclient=new DefaultHttpClient(); 
     httppost= new HttpPost("http://aaaa.com/app/insertProduct.php"); 
     // Url del Servidor 

     try { 
      httppost.setEntity(new UrlEncodedFormEntity(params)); 
      httpclient.execute(httppost); 
      return true; 
     } catch (UnsupportedEncodingException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } catch (ClientProtocolException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
     return false; 
    } 

    private void serverUpdate(){ 
     if (file.exists()) 
      new ServerUpdate().execute(); 
     else 
      Toast.makeText(UploadProduct.this, "Debes de hacer una foto", 
        Toast.LENGTH_LONG).show(); 

    } 

    class ServerUpdate extends AsyncTask<String,String,String> { 

     ProgressDialog pDialog; 
     @Override 
     protected String doInBackground(String... arg0) { 
      Boolean b=uploadFoto(imageFileName); 
      if(onInsert()&& b) 
       runOnUiThread(new Runnable(){ 
        @Override 
        public void run() { 
         // TODO Auto-generated method stub 
         Toast.makeText(UploadProduct.this, "Exito al subir la imagen", 
           Toast.LENGTH_LONG).show(); 
        } 
       }); 
      else 
       runOnUiThread(new Runnable(){ 
        @Override 
        public void run() { 
         // TODO Auto-generated method stub 
         Toast.makeText(UploadProduct.this, "Sin exito al subir la imagen", 
           Toast.LENGTH_LONG).show(); 
        } 
       }); 
      return null; 
     } 
     protected void onPreExecute() { 
      super.onPreExecute(); 
      pDialog = new ProgressDialog(UploadProduct.this); 
      pDialog.setMessage("Actualizando Servidor, espere..."); 
      pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); 
      pDialog.show(); 
     } 
     protected void onPostExecute(String result) { 
      super.onPostExecute(result); 
      pDialog.dismiss(); 
     } 

    } 

我upload.php的

<?php 

    $ruta = "app/imagenes/" .basename($_FILES['foto']['name']); 
    if(move_uploaded_file($_FILES['foto']['tmp_name'], $ruta)){ 
      echo "success"; 
     } else{ 
      echo "fail"; 
     } 
    ?> 
+0

看看这个答案 - http://*.com/questions/11164398/android-upload-video -to-remote-server-using-http-multipart-form-data – Zain

+0

谢谢@zain我看到你的帖子,但我认为问题出在'upload.php'中。 – tipiwiny

就我而言,我不得不把绝对路径在我的PHP文件。

upload.php的

<?php 
// En versiones de PHP anteriores a 4.1.0, $HTTP_POST_FILES debe utilizarse en lugar 
// de $_FILES. 

$uploaddir = '/var/www/vhosts/aaaa.com/httpdocs/app/imagenes/'; 
$uploadfile = $uploaddir . basename($_FILES['foto']['name']); 

echo 'bien'; 
if (move_uploaded_file($_FILES['foto']['tmp_name'], $uploadfile)) { 
    echo "El archivo es válido y fue cargado exitosamente.\n"; 
} else { 
    echo "¡Posible ataque de carga de archivos!\n"; 
    echo $_SERVER['DOCUMENT_ROOT']; 
} 

echo 'Aquí hay más información de depurado:'; 


?> 

感谢您的帮助

$profilepic = $_FILES ['foto'] ['name']; 
    // let if jpeg image 
    $extension='.jpeg'; 


    function saveImageInServer($profileimage, $email,$extension) { 
     $dir = '/var/www/users'; 
     if (is_dir ($dir) == false) { 
      mkdir ($dir); 
     } 
     chmod ($dir, 0777); 
     $target_Path = $dir . "/" . $email . "." . $extension; 
     move_uploaded_file ($_FILES ['proiflepic'] ['tmp_name'], $target_Path); 
     chmod ($target_Path, 0777); 
    } 
+0

我证明你的代码!当'upload.php'被执行时,我不会创建任何新的路径。我不明白这个问题。谢谢! – tipiwiny