带有图片列表的Android分段上传

时间:2014-09-19 10:34:56

标签: android file-upload upload

我想上传到服务器的图片列表

我正在使用httpmime,这是代码:

for(File file : gs.id_img) {
            builder.addPart("id_img[]", new FileBody(file)); 
        }

但是在后端似乎无法获得后期值,如何解决?感谢

1 个答案:

答案 0 :(得分:1)

你必须像这样工作

public void connectForMultipart() throws Exception {
    con = (HttpURLConnection) ( new URL(url)).openConnection();
    con.setRequestMethod("POST");
    con.setDoInput(true);
    con.setDoOutput(true);
    con.setRequestProperty("Connection", "Keep-Alive");
    con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
    con.connect();
    os = con.getOutputStream();
}

public void addFormPart(String paramName, String value) throws Exception {
    writeParamData(paramName, value);
}

public void addFilePart(String paramName, String fileName, byte[] data) throws Exception {
    os.write( (delimiter + boundary + "\r\n").getBytes());
    os.write( ("Content-Disposition: form-data; name=\"" + paramName +  "\"; filename=\"" + fileName + "\"\r\n"  ).getBytes());
    os.write( ("Content-Type: application/octet-stream\r\n"  ).getBytes());
    os.write( ("Content-Transfer-Encoding: binary\r\n"  ).getBytes());
    os.write("\r\n".getBytes());

    os.write(data);

    os.write("\r\n".getBytes());
}   
public void finishMultipart() throws Exception {
    os.write( (delimiter + boundary + delimiter + "\r\n").getBytes());
}

我已将Content-Type: application/octet-stream\r\n"更改为Content-Type: image/jpeg\r\n\r\n并且有效:)