簡體   English   中英

上傳圖像並通過Android應用發送帶有$ _POST的文本

[英]Upload an image AND send text with $_POST through an android app

我必須將圖像上傳到服務器,但還要發送一些文本。 這是我所做的,但是不起作用:

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結合使用。 而是添加所有字符串字段,因為它是Multipart的一部分。

看一個例子: Apache HttpClient制作多部分表單

暫無
暫無

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

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