Android multipart upload with image list [closed]

2019-08-28 09:28发布

There is a image list I would like to upload to the server

I am using httpmime , and here is the code:

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

But in the backend it seems can not get the post value, how to fix it? thanks

1条回答
Luminary・发光体
2楼-- · 2019-08-28 10:00

you have to work like this

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());
}

I have changed Content-Type: application/octet-stream\r\n" to Content-Type: image/jpeg\r\n\r\n and it worked :)

查看更多
登录 后发表回答