android中的多部分数据上传无效

时间:2013-05-06 20:57:22

标签: android upload multipart

我正在尝试在Android上传多部分数据,但我的代码无效。我的代码如下。我的上传信息主要是文本字段。所以我保留了一个HashMap,以便密钥包含字段名称,值将包含字段值。但我的解决方案不起作用。请有人关注我在这里做错了什么。

public static boolean uploadMultipartData(String urlString, HashMap<String, Object> dataMap){
    HttpURLConnection urlConnection = null;
    DataOutputStream outStream = null;
    DataInputStream inStream = null;

    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = "---------------------------265001916915724";



    if (dataMap != null){
        try {
            StringBuffer data = new StringBuffer();
            URL url = new URL(urlString);
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setDoInput(true);
            urlConnection.setDoOutput(true);
            urlConnection.setUseCaches(false);

            urlConnection.setRequestMethod("POST");
            urlConnection.setRequestProperty("Connection", "Keep-Alive");
            urlConnection.setRequestProperty("Content-Type",
                    "multipart/form-data;boundary=" + boundary);

            outStream = new DataOutputStream(urlConnection.getOutputStream());

            for (Entry<String, Object> entry : dataMap.entrySet()) {
                String key = entry.getKey();
                Object value = entry.getValue();

                outStream.writeBytes(twoHyphens + boundary + lineEnd);
                outStream.writeBytes("Content-Disposition: form-data; name=\"" + key + "\""
                                + lineEnd);
                outStream.writeBytes(value.toString());
                outStream.writeBytes(lineEnd);
            }
            outStream.writeBytes(twoHyphens + boundary + twoHyphens);
            outStream.flush();
        } 
        catch (MalformedURLException e) {
            Log.e("DEBUG", "[MalformedURLException while sending data]");
        } 
        catch (IOException e) {
            Log.e("DEBUG", "[IOException while sending data]");
        }
        finally{
            try {                   
                outStream.close();
                urlConnection.disconnect();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

我可以发送一张图片。但是当我想要将文本字段值与图像一起发送时,它会产生问题。我的帖子请求如下 -

-----------------------------265001916915724
Content-Disposition: form-data; name="file"

IMAGE DATA GOES HERE

-----------------------------265001916915724

Content-Disposition: form-data; name="location"

LOCATION GOES HERE

-----------------------------265001916915724--