public class UploadImgUtils {
public static final StringMULTIPART_FORM_DATA ="Multipart/form-data"; // 指明要上传的文件格式
public static void okHttpUpload(String url,List keyList,List valueList,
String fileKeyName,
List imgList,
final UploadCallback callback){
// 初始化请求体对象,设置Content-Type以及文件数据流
MultipartBody.Builder builder =new MultipartBody.Builder()
.setType(MultipartBody.FORM); // multipart/form-data
for(int i=0;i
builder.addFormDataPart(keyList.get(i),valueList.get(i));
}
if(imgList!=null){
if(!imgList.isEmpty()){
for(int i=0;i
File mFile =new File(imgList.get(i));
RequestBody mRequestFile =// 根据文件格式封装文件
RequestBody.create(MediaType.parse(MULTIPART_FORM_DATA), mFile);
builder.addFormDataPart(fileKeyName,mFile.getName(),mRequestFile);
}
}
}
RequestBody requestBody =builder.build();
// 封装OkHttp请求对象,初始化请求参数
Request request =new Request.Builder()
.url(APIField.getAppServiceUrl()+"/4S-web/"+url)// 上传url地址
.post(requestBody)// post请求体
.build();
final okhttp3.OkHttpClient.Builder httpBuilder =new OkHttpClient.Builder();
OkHttpClient okHttpClient = httpBuilder
.connectTimeout(100, TimeUnit.SECONDS)// 设置请求超时时间
.writeTimeout(150, TimeUnit.SECONDS)
.build();
// 发起异步网络请求
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onResponse(Call call, okhttp3.Response response)throws IOException {
if (callback !=null){
callback.onResponse(call, response);
}
}
@Override
public void onFailure(Call call, IOException e) {
if (callback !=null){
callback.onFailure(call, e);
}
}
});
}
/**
* 根据uri获取当前路径
*/
public static StringtoGetStringFOrUri(Context context,Uri uri, String selection, String[] selectionArgs){
Cursor cursor =null;
final String column ="_data";//路径保存在downloads表中的_data字段
final String[] projection = {column};
try {
cursor =context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
if (cursor !=null && cursor.moveToFirst()) {
final int column_index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(column_index);
}
}catch (Exception e) {
e.printStackTrace();
}finally {
if (cursor !=null)
cursor.close();
}
return null;
}
}