php - 通过 Android 应用上传图片并使用 $_POST 发送文本

标签 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

为什么它不起作用?

感谢您的协助!

最佳答案

您不能结合使用 UrlEncoded 和 Multipart。相反,将所有字符串字段添加为它自己的多部分的一部分。

看这里的例子: Apache HttpClient making multipart form post

关于php - 通过 Android 应用上传图片并使用 $_POST 发送文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18601947/

相关文章:

android - 导入时出现 ClassNotFoundException。阿尔

android - Gradle:不推荐使用的动态属性。如何重新配置​​?

php - $_POST 值返回空数组

php - 使用 codeigniter 在 mysql 中连接

android - 如何从 Android 2.3 上的 ActionBarSherlock 溢出菜单中删除图标?

angular - HTTP post 405 方法不允许

asp.net - 在 .net 3.5 解决方案中发布到 Web 服务

php - 从文件夹加载图像列表

PHP:shell_exec 既未定义也未禁用

c# - 为什么我的 HTTP POST 正文内容被接收/处理为 NULL?