表单中上传文件、压缩上传图片

表单上传文件,详见代码:

public boolean edit(String url, List<NameValuePair> params) {  //name是字段名,value是文件地址

HttpClient httpClient = new DefaultHttpClient();
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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值