第一 android手机端post上传图片 (也可以是图片,文字混合或者图片数组等组合形式,这里服务端演示获取图片)
下面代码中写了多种组合方式
/**
* 上传文件 测试多张图片和文字混合上传
*
* @param actionUrl 接口地址
*/
public <T> void upLoadFileduo(Context context, String actionUrl, String filename1,String filename2, final BaseCallback<T> callBack) {
callBack.onBeforeRequest(null);
String requestUrl = actionUrl;
//创建File
File file1 = CompressHelper.getDefault(context).compressToFile(new File(filename1));
File file2 = CompressHelper.getDefault(context).compressToFile(new File(filename2));
// ByteArrayBody bab1 = new ByteArrayBody(PhotoTools.File2byte(filename1), "lihuanfront.jpg");
// ByteArrayBody bab2 = new ByteArrayBody(PhotoTools.File2byte(filename2), "lihuanopp.jpg");
MediaType type=MediaType.parse("application/octet-stream");//“text/xml;charset=utf-8”
RequestBody fileBody1=RequestBody.create(type,file1);
RequestBody fileBody2=RequestBody.create(type,file2);
//创建RequestBody
RequestBody multipartBody = new MultipartBody.Builder()
.setType(MultipartBody.ALTERNATIVE)
//一样的效果
// .addPart(Headers.of(
// "Content-Disposition",
// "form-data; name=\"params\"")
// ,paramsBody)
// .addPart(Headers.of(
// "Content-Disposition",
// "form-data; name=\"file\"; filename=\"plans.xml\"")
// , fileBody)
// .addPart(Headers.of(
// "Content-Disposition",
// "form-data; name=\"file\"; filename=\"plans.xml\"")
// , fileBody)
//一样的效果
// .addFormDataPart("realName", "李")
// .addFormDataPart("idCard", "510322198602030429")
// .addFormDataPart("idFrontFileName", "lihuanfront.png")
// .addFormDataPart("idOppFileName", "lihuanopp.png")
// .addFormDataPart("code", "15040070175")
// .addFormDataPart("idFrontBytes", "lihuanfront.png", fileBody1)
.addFormDataPart("idOppBytes", "lihuanopp.png",fileBody2 )
.build();
Request request = new Request.Builder().url("http://192.168.1.132:8080/filepost")//http://106.13.99.207/f/web/app/zctPersonalIdentity/save
.addHeader("User-Agent", "android")
.header("Content-Type", "text/html; charset=utf-8;")
.post(multipartBody)//传参数、文件或者混合,改一下就行请求体就行
.build();
final Call call = mHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
callBack.onFailure(null, e);
callbackError(callBack, null, -1, null);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
callBack.onResponse(response);
if (response.isSuccessful()) {
String string = response.body().string();
Log.e(TAG, "response ----->" + string);
callbackSuccess(callBack, response, string);
} else {
// failedCallBack("上传失败", callBack);
callbackError(callBack, response, response.code(), null);
}
}
});
}
第二 服务端接受(只写了接受一个图片,其他参数和别的一样 主要文件接收是
MultipartFile 不是 File
)