通过Android应用程序上传图像并使用$ _POST发送文本

时间:2013-09-03 21:39:15

标签: php android post httprequest image-uploading

我必须将图像上传到我的服务器,但也要发送一些文字。这就是我所做的,但它不起作用:

String  UploadImage(Bitmap bm) {
    String resp = null;
    try {  
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        bm.compress(CompressFormat.JPEG, 75, bos);
        byte[] data = bos.toByteArray();

        HttpClient httpClient = new DefaultHttpClient();
        HttpPost postRequest = new HttpPost("myserver.com/add.php");
        String rndName =generateSessionKey(15);

        List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(1);
        nameValuePair.add(new BasicNameValuePair("filename",rndName));
        nameValuePair.add(new BasicNameValuePair("email",email));

        UrlEncodedFormEntity form;
        form = new UrlEncodedFormEntity(nameValuePair);
        form.setContentEncoding(HTTP.UTF_8);
        try {
            postRequest.setEntity((HttpEntity) new UrlEncodedFormEntity(nameValuePair,"UTF-8"));
        } catch (UnsupportedEncodingException e) {
            // writing error to Log
            e.printStackTrace();
        }

        ByteArrayBody bab = new ByteArrayBody(data,rndName+".jpg");

        MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        reqEntity.addPart("uploaded", bab);
        //reqEntity.addPart("photoCaption", new StringBody("sfsdfsdf"));
        postRequest.setEntity(reqEntity);
        HttpResponse response = httpClient.execute(postRequest);
        BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
        String sResponse;
        StringBuilder s = new StringBuilder();
        while ((sResponse = reader.readLine()) != null) {
            s = s.append(sResponse);
        }
        resp=s.toString();
    } catch (Exception e) {
        // handle exception here
        Log.e(e.getClass().getName(), e.getMessage());
    }
    return resp;
}

服务器无法获得filenameemail

为什么它不起作用?

感谢您的协助!

1 个答案:

答案 0 :(得分:1)

您无法合并UrlEncoded和Multipart。相反,添加所有字符串字段,因为它是Multipart的一部分。

在这里查看示例: Apache HttpClient making multipart form post