如何通过MultipartEntity将数据发送到服务器

时间:2013-11-30 21:41:39

标签: php android multipartentity

正在开发一个可以将图像和用户的名字和第二个名称发送到服务器的应用程序。应用程序可以将图像发送到服务器,但我无法检索用户的名字和第二个名称。以下是我的代码

的java

HttpClient httpClient = new DefaultHttpClient();
            HttpContext localContext = new BasicHttpContext();
            HttpPost httpPost = new HttpPost(
                    "http://192.168.1.144/app_api/samplerEG.php");

            MultipartEntity entity = new MultipartEntity(
                    HttpMultipartMode.BROWSER_COMPATIBLE);

            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            bitmap.compress(CompressFormat.JPEG, 100, bos);
            byte[] data = bos.toByteArray();
            entity.addPart("fname", new StringBody(user_fname));
            entity.addPart("lname", new StringBody(user_lname));
            entity.addPart("file", new ByteArrayBody(data, "picture.jpg"));
            httpPost.setEntity(entity);
            HttpResponse response = httpClient.execute(httpPost,
                    localContext);
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(
                            response.getEntity().getContent(), "UTF-8"));

            String sResponse = reader.readLine();
            return sResponse;

和php是

         $fname = $_POST["fname"];
         $lname = $_POST["lname"];
         $date_of_birth = $_POST["dob"];
         $pnumber = $_POST["pnumber"];
         $district_name = $_POST["district_name"];
         $gender = basename($_POST['gender']);
         $picture =  md5(basename($_FILES['file']['name'])).".jpg";

我哪里可能出错

1 个答案:

答案 0 :(得分:0)

FileBody uploadVideo = new FileBody(new File(filePath));
     MultipartEntity reqEntity = new MultipartEntity();
     reqEntity.addPart( "file", uploadVideo );
     try {
        reqEntity.addPart( "ToId", new StringBody(contactId));
        reqEntity.addPart( "type", new StringBody("1"));
        reqEntity.addPart( "MsgText", new StringBody(""));
        reqEntity.addPart( "FromId", new StringBody(pref.getUserId()));
        reqEntity.addPart( "UniqueId", new StringBody(ControllerActivity.DEVICE_UNIQUE_ID));
    } catch (UnsupportedEncodingException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

您只需使用FileBody而不是