项目中需要进行上传多张图片,比如说,发表文章的时候最多可以上传9张图片。
List<File> filelist = new ArrayList<File>(); for (int i = 0; i < filePath.length; i++) { <span style="white-space:pre"> </span>filelist.add(new File(filePath[i])); } RequestParams params = new RequestParams(); String ts = DateUtils.getTimeStamp(10); params.addBodyParameter("apipwd",EncryptUtils.md5(ConstDef.API_PWD + ts)); params.addBodyParameter("apitime", ts); params.addBodyParameter("imgfile[]", filelist, "image/jpeg");
a、这里发现了,addBodyParameter()会是HashMap,如果写成params.addBodyParameter("imgfile", filelist, "image/jpeg");只会留下最后一个。
然后就,修改看看HashMap如何实现一个Key对应多个value,感觉这种方法不好。就使用
private HashMap<String, ArrayList<ContentBody>> mutiFileParams;解决这个问题。
b、params.addBodyParameter("imgfile", filelist, "image/jpeg");这里每次发现只有最后一张图片被服务器接收到了;
c、第二怀疑是否是
public void addBodyParameter(String key, List<File> fileList) { if (mutiFileParams == null) { mutiFileParams = new HashMap<String, ArrayList<ContentBody>>(); } ArrayList<ContentBody> fileBodies = null; if (fileList != null) { fileBodies = new ArrayList<ContentBody>(); for (File file : fileList) { fileBodies.add(new FileBody(file)); } } mutiFileParams.put(key, fileBodies); } public void addBodyParameter(String key, List<File> fileList, String mimeType) { if (mutiFileParams == null) { mutiFileParams = new HashMap<String, ArrayList<ContentBody>>(); } ArrayList<ContentBody> fileBodies = null; if (fileList != null) { fileBodies = new ArrayList<ContentBody>(); for (File file : fileList) { fileBodies.add(new FileBody(file, mimeType)); } } mutiFileParams.put(key, fileBodies); }在文件RequestParams.java中修改。
else if (mutiFileParams != null && !mutiFileParams.isEmpty()) { MultipartEntity multipartEntity = new MultipartEntity( HttpMultipartMode.STRICT, null, Charset.forName(charset)); if (bodyParams != null && !bodyParams.isEmpty()) { for (NameValuePair param : bodyParams) { try { multipartEntity.addPart(param.getName(), new StringBody(param.getValue())); } catch (UnsupportedEncodingException e) { LogUtils.e(e.getMessage(), e); } } } for (ConcurrentHashMap.Entry<String, ArrayList<ContentBody>> entry : mutiFileParams .entrySet()) { ArrayList<ContentBody> filelist = entry.getValue(); if (filelist != null) { for (ContentBody contentBody : filelist) { multipartEntity.addPart(entry.getKey(), contentBody); } } } result = multipartEntity; }