簡體   English   中英

如何在Android中使用HttpPost發送圖像

[英]How to send Image with HttpPost in Android

我必須通過HttpPost將圖片發送到php服務器,但是我的代碼無法正常工作...

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"

任何建議和幫助將不勝感激。

您可以這樣做。.我嘗試過,它對我有用

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;
 }
?>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM