昨天在项目上遇到一个需求,固定两个文件参数的上传,但是有的时候可能有个文件参数是空的,以前没遇到过这种需求,问度娘也无果。最后自己慢慢尝试出来的,心累呀。
具体代码实现可能写出来的代码有点儿low,以后改善就好了。存在空文件的情况是mediaList.size()为1的时候。
public static MultipartBody.Part createFormData(String name, String value) {
return createFormData(name, (String)null, RequestBody.create((MediaType)null, value));
}
public static MultipartBody.Part createFormData(String name, String filename, RequestBody body) {
if(name == null) {
throw new NullPointerException("name == null");
} else {
StringBuilder disposition = new StringBuilder("form-data; name=");
MultipartBody.appendQuotedString(disposition, name);
if(filename != null) {
disposition.append("; filename=");
MultipartBody.appendQuotedString(disposition, filename);
}
return create(Headers.of(new String[]{"Content-Disposition", disposition.toString()}), body);
}
}
以上是构造MultipartBody.Part的两种方法,我们会发现有个方法可以不用传RequestBody对象,这不正是我们想要的吗,bingo。
网友评论