如何在Android中使用HttpPost发送图像

时间:2012-06-20 04:47:35

标签: java android apache-httpcomponents

我必须通过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) {
}
}

Post方法的URL格式是否正确?或者它应该是这样的...... URL="http://xyz.com.au/abc/users/webappadpost"

任何建议和帮助将不胜感激。

1 个答案:

答案 0 :(得分: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;
 }
?>