前幾天開發安卓要用到文件批量上傳,就是上傳圖片,視頻,文件之類的用到Xutil3框架,用
RequestParams params = new RequestParams(url);
params.addParameter("file", new File(file));
只能上傳單張,不可能上傳多張
於是采用for循環,
for(int i=0;i<fileList.size();i++){
params.addParameter("file", new File(fileList.get(i)));
}
params.setMultipart(true);
x.http().post(params, new org.xutils.common.Callback.CacheCallback<String>() {
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
@Override
public void onSuccess(String s) {
try {
JSONObject obj = new JSONObject(s);
}
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onError(Throwable throwable, boolean b) {
Toast.makeText(AttendanceActivity.this, "錯誤:" + throwable.getMessage(), Toast.LENGTH_SHORT).show();
}
@Override
public void onCancelled(CancelledException e) {
}
@Override
public void onFinished() {
}
@Override
public boolean onCache(String s) {
return false;
}
});
}
還是不行后發現研究api 發現文件需要
multipart/data 剛好xutil3 有
MultipartBody這個類,所有就有了
File file = new File(upFileName);
List<KeyValue> list = new ArrayList<KeyValue>();
list.add(new KeyValue("file",file));
MultipartBody body=new MultipartBody(list,"UTF-8");
params.setRequestBody(body);
params.setMultipart(true);
x.http().post(params, new org.xutils.common.Callback.CacheCallback<String>() {
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
@Override
public void onSuccess(String s) {
try {
JSONObject obj = new JSONObject(s);
}
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onError(Throwable throwable, boolean b) {
Toast.makeText(AttendanceActivity.this, "錯誤:" + throwable.getMessage(), Toast.LENGTH_SHORT).show();
}
@Override
public void onCancelled(CancelledException e) {
}
@Override
public void onFinished() {
}
@Override
public boolean onCache(String s) {
return false;
}
});
}
關鍵代碼
List<KeyValue> list = new ArrayList<KeyValue>();
list.add(new KeyValue("file",file));
MultipartBody body=new MultipartBody(list,"UTF-8");
params.setRequestBody(body);
這樣就完美解決xutil3 批量文件上傳了