前几天开发安卓要用到文件批量上传,就是上传图片,视频,文件之类的用到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 批量文件上传了