表单上传文件,详见代码:
HttpClient httpClient = new DefaultHttpClient();public boolean edit(String url, List<NameValuePair> params) { //name是字段名,value是文件地址
HttpContext localContext = new BasicHttpContext();
HttpPut httpPut = new HttpPut(url);
try {
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
for (int index = 0; index < params.size(); index++) {
if (params.get(index).getName()
.equalsIgnoreCase("image")) {
entity.addPart(params.get(index).getName(),
new FileBody(ImageUtils.zoomToFix(params.get(index).getValue(), 200))); //zoomToFix是自己封装的压缩上传图片的方法,具体见下文
} else {
entity.addPart(
params.get(index).getName(),
new StringBody(params.get(index).getValue(), Charset.forName("UTF-8")));
}
}
httpPut.setEntity(entity);
HttpResponse response = httpClient.execute(httpPut, localContext);
ReturnMsg<User> msg = getReturnMsg(response.getEntity().getContent());
if(msg != null && msg.getRespCode() == ReturnCode.SUCCESS) {
return true;
}
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
压缩上传图片:
private static BitmapFactory.Options options = new BitmapFactory.Options();
/**
* 压缩图片为固定高度
* @param filePath 图片地址
* @param h 指定高度
* @return
*/
public static File zoomToFix(String filePath, int h) {
File file = new File(filePath);
try {
options.inJustDecodeBounds = true; // 先设置预读图片,既只读取大小信息
Bitmap bitmap = BitmapFactory.decodeFile(filePath, options);
options.inJustDecodeBounds = false; // 读出大小信息后改为非预读
int be = options.outWidth/h; // 计算缩放倍数
if(be <= 0) be = 1;
options.inSampleSize = be; // 设置缩放,可惜只能是整数
bitmap = BitmapFactory.decodeFile(filePath, options); // 根据缩放比实际读取图片
FileOutputStream fos = new FileOutputStream(file); // 保存图片文件
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
} catch (FileNotFoundException e) {
Log.e("ImageUtils", e.getMessage(), e);
}
return file;
}