2012-06-20 6 views
1

я должен отправить изображение на PHP сервер через HttpPost, но мой код не работает ...Как отправить изображение с HttpPost в Android

public void postAddToServer() { 

    String URL="http://xyz.com.au/abc/users/webappadpost/?userid=12531&listtype=2&listcatid=2&listsubcatid=3&listtitle=testTitle&listdesc=justDemo&listprice=1&listsuburb=adelate&listphone=9895623148&listavailable=1&listcondtn=1&listoldcondtn=3"; 

    ByteArrayOutputStream bao = new ByteArrayOutputStream(); 
    post_add_bitmap_image.compress(Bitmap.CompressFormat.JPEG, 90, bao); 
    byte [] ba = bao.toByteArray(); 
    String baImage=Base64.encodeBytes(ba); 

    try { 
     String lineEnd = "\r\n"; 
     String twoHyphens = "--"; 
     String boundary = "xxxxxxxx"; 
     //String EndBoundary = ""; 
     String str = twoHyphens + boundary + lineEnd; 

     String str4 = "Content-Disposition: form-data; name=\"image\""; 
     String str5 = "Content-Type: image/jpg"; 
     String str6 = twoHyphens + boundary + twoHyphens; 

     String StrTotal ="\r\n" + str + str4 + "\r\n" +"\r\n"+ baImage + "\r\n" + str6; 

     HttpPost post = new HttpPost(URL); 
     post.addHeader("Content-Type","multipart/form-data;boundary="+boundary); 
     post.addHeader("Content-Type","image/jpg"); 

     StringEntity se = new StringEntity(StrTotal); 
     se.setContentEncoding("UTF-8"); 

     post.setEntity(se); 

     HttpClient client= new DefaultHttpClient(); 
     HttpResponse response = client.execute(post); 

     HttpEntity getResEntity=response.getEntity(); 
     System.out.println("RESPONSE getResEntity : "+getResEntity.toString()); 
     String result=""; 

     if(getResEntity!=null){ 
      result=EntityUtils.toString(getResEntity); 
      System.out.println("result from server: "+result); 

      if(result!=null){ 
       JSONObject object=new JSONObject(result); 
       statusFlag=object.getString("status"); 
       statusFlagMessage=object.getString("message"); 
      } 
      else{ 
       System.out.println("NULL response from server."); 
      }      
     } 
    } 
    catch (RuntimeException e) { 
} 
    catch (Exception e) { 
} 
} 

ли URL в правильной форме для Post метода? Или это должно быть что-то вроде этого ... URL="http://xyz.com.au/abc/users/webappadpost"

Любое предложение и помощь будут оценены.

ответ

0

вы можете сделать, как это .. я попробовал это, и это работает для меня

private void uploadImage() { 
    // TODO Auto-generated method stub 

     try 
     { 
     String extStorageDirectory = Environment.getExternalStorageDirectory().toString()+"/SurveyFiles/"; 
     pathToOurFile=extStorageDirectory+fileName+".jpg"; 
     //Toast.makeText(this, pathToOurFile.toString(), 600).show(); 
     //Toast.makeText(this, pathToOurFile, 600).show(); 
     FileInputStream fileInputStream = new FileInputStream(new File(pathToOurFile)); 

     URL url = new URL(urlServer); 
     connection = (HttpURLConnection) url.openConnection(); 

     // Allow Inputs & Outputs 
     connection.setDoInput(true); 
     connection.setDoOutput(true); 
     connection.setUseCaches(false); 

     // Enable POST method 
     connection.setRequestMethod("POST"); 

     connection.setRequestProperty("Connection", "Keep-Alive"); 
     connection.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary); 

     outputStream = new DataOutputStream(connection.getOutputStream()); 
     outputStream.writeBytes(twoHyphens + boundary + lineEnd); 
     outputStream.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + pathToOurFile +"\"" + lineEnd); 
     outputStream.writeBytes(lineEnd); 

     bytesAvailable = fileInputStream.available(); 
     bufferSize = Math.min(bytesAvailable, maxBufferSize); 
     buffer = new byte[bufferSize]; 

     // Read file 
     bytesRead = fileInputStream.read(buffer, 0, bufferSize); 

     while (bytesRead > 0) 
     { 
     outputStream.write(buffer, 0, bufferSize); 
     bytesAvailable = fileInputStream.available(); 
     bufferSize = Math.min(bytesAvailable, maxBufferSize); 
     bytesRead = fileInputStream.read(buffer, 0, bufferSize); 
     } 

     outputStream.writeBytes(lineEnd); 
     outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); 

     // Responses from the server (code and message) 
     connection.getResponseCode(); 
     connection.getResponseMessage(); 

     fileInputStream.close(); 
     outputStream.flush(); 
     outputStream.close(); 
     } 
     catch (Exception ex) 
     { 
     //Exception handling 
     } 

PathtoOurFile путь изображения и хотите, чтобы загрузить и urlserver путь ур файла PHP

вот что php-файл

<?php 
// Where the file is going to be placed 
$target_path = "path where u need to store on server"; 

/* Add the original filename to our target path. 
Result is "uploads/filename.extension" */ 
$target_path = $target_path . basename($_FILES['uploadedfile']['name']); 

    if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) { 
    echo "The file ". basename($_FILES['uploadedfile']['name']). 
    " has been uploaded"; 
    } else{ 
    echo "There was an error uploading the file, please try again!"; 
    echo "filename: " . basename($_FILES['uploadedfile']['name']); 
    echo "target_path: " .$target_path; 
} 
?> 
+0

Спасибо за ваш добрый и быстрый ответ. Я пытаюсь это тем временем, дайте мне знать, что мой URL-адрес okk ?? Я спросил после моего Кодекса. пожалуйста, проверьте. спасибо –

+0

URL ur не выглядит нормально для меня. где exacly u хотите сохранить изображение на сервере ??? –

+0

Я тоже чувствую то же самое. Серверная сторона ожидает что-то вроде этого POST: Array ([fname] => werewrwrr [submit] => Отправить) GET: Array() FILE: Array ([upload] => Array ([name] => Водяные лилии. jpg [type] => image/jpeg [tmp_name] =>/tmp/phptbDtnD [error] => 0 [size] => 83794)) Они ожидают Файл –

Смежные вопросы