Android 通过Base64上传图片到服务器
之前做上传图片是采用HttpServlet上传,不过用了一下Base64上传图片后,感觉比HttpServlet方便很多,大家也可以跟着尝试一下。
前台图片处理:(传Bitmap对象即可)
/**
* 通过Base32将Bitmap转换成Base64字符串
* @param bit
* @return
*/
public String Bitmap2StrByBase64(Bitmap bit){
ByteArrayOutputStream bos=new ByteArrayOutputStream();
bit.compress(CompressFormat.JPEG, , bos);//参数100表示不压缩
byte[] bytes=bos.toByteArray();
return Base64.encodeToString(bytes, Base64.DEFAULT);
}
前台发送数据:(調用setImgByStr()方法,第一個參數imgStr 为Bitmap转成Base64的字符串,第二个参数imgName为图片的名字,包含后缀名.jpg)
public static String host = "http://192.168.1.166:8080/ImageServer/"; public static String getContent(String url) throws Exception { StringBuilder sb = new StringBuilder(); HttpClient client = new DefaultHttpClient();
HttpParams httpParams = client.getParams();
// 设置网络超时参数
HttpConnectionParams.setConnectionTimeout(httpParams, ); HttpConnectionParams.setSoTimeout(httpParams, );
HttpResponse response = client.execute(new HttpGet(url));
HttpEntity entity = response.getEntity();
if (entity != null) {
BufferedReader reader = new BufferedReader(new InputStreamReader(
entity.getContent(), "UTF-8"), ); String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
reader.close(); } return sb.toString();
}
public static HttpResponse post(Map<String, Object> params, String url) { HttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.addHeader("charset", HTTP.UTF_8);
httpPost.setHeader("Content-Type",
"application/x-www-form-urlencoded; charset=utf-8");
HttpResponse response = null;
if (params != null && params.size() > ) {
List<NameValuePair> nameValuepairs = new ArrayList<NameValuePair>();
for (String key : params.keySet()) {
nameValuepairs.add(new BasicNameValuePair(key, (String) params
.get(key)));
}
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuepairs,
HTTP.UTF_8));
response = client.execute(httpPost);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (RuntimeException e) {
e.printStackTrace();
}
} else {
try {
response = client.execute(httpPost);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} return response; }
public static Object getValues(Map<String, Object> params, String url) {
String token = "";
HttpResponse response = post(params, url);
if (response != null) {
try {
token = EntityUtils.toString(response.getEntity());
response.removeHeaders("operator");
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return token;
}
public static Object setImgByStr(String imgStr,String imgName){
String url = host+"channel-uploadImage.action";
Map<String,Object> params = new HashMap<String, Object>();
params.put("imgStr", imgStr);
params.put("imgName", imgName);
return getValues(params, url);
}
后台接收数据:
public void uploadPhoto() {
//获取存储路径
HttpServletRequest request = ServletActionContext.getRequest();
String path = ServletActionContext.getServletContext().getRealPath("/")+"upload";
File file = new File(path);
if(!file.exists()){
file.mkdir();
}
String imgPath = path + request.getParameter("imgName");
String imgStr = request.getParameter("imgStr");
boolean flag = string2Image(imgStr, imgPath);
JacksonUtil.responseJSON(response, flag);
}
后台图片处理:
/**
* 通过BASE64Decoder解码,并生成图片
* @param imgStr 解码后的string
*/
public boolean string2Image(String imgStr, String imgFilePath) {
// 对字节数组字符串进行Base64解码并生成图片
if (imgStr == null)
return false;
try {
// Base64解码
byte[] b = new BASE64Decoder().decodeBuffer(imgStr);
for (int i = ; i < b.length; ++i) {
if (b[i] < ) {
// 调整异常数据
b[i] += ;
}
}
// 生成Jpeg图片
OutputStream out = new FileOutputStream(imgFilePath);
out.write(b);
out.flush();
out.close();
return true;
} catch (Exception e) {
return false;
}
}
OK ! 如果成功上传前端会接收到true ,反之失败false。希望对大家有所帮助!
Android 通过Base64上传图片到服务器的更多相关文章
- 通过android 客户端上传图片到服务器
昨天,(在我的上一篇博客中)写了通过浏览器上传图片到服务器(php),今天将这个功能付诸实践.(还完善了服务端的代码) 不试不知道,原来通过android 向服务端发送图片还真是挺麻烦的一件事. 上传 ...
- ios客户端base64上传图片到java服务器遇到的问题
由于base64位包含了“+”和“\”两个特殊符号,导致ios编码后上传图片到服务器,服务器解码以后的值会不一致,导致图片损坏. 解决办法:重写Base64类,用“(”和“)”替换“+”和“\”两个特 ...
- Android 上传图片到服务器二--------调用相机7.0以上权限问题
[目录] (一)上传图片到服务器一 ---------------------------------Android代码 (二)上传图片到服务器二--------------------------- ...
- Android 上传图片到服务器 okhttp一
[目录] (一)上传图片到服务器一 ---------------------------------Android代码 (二)上传图片到服务器二--------------------------- ...
- android上传文件到服务器
package com.spring.sky.image.upload.network; import java.io.DataOutputStream; import java.io.File; i ...
- Android webview实现上传图片的效果(图片压缩)
mainactivity代码 package com.bwie.webviewupload; import java.io.ByteArrayInputStream; import java.io.B ...
- android -上传文件到服务器
android上传文件到服务器 重点:最好是设置好content-type这些参数的配置! package com.spring.sky.image.upload.network; ...
- Java android DES+Base64加密解密
服务器与客户端加密解密传输, 中间遇到各种坑,客户端无论用AES还是DES解密时都会出现错误,后来才看到好多人说要用AES/DES加完密后还要BASE64加密,照做时发现android和java的Ba ...
- Android操作HTTP实现与服务器通信(转)
Android操作HTTP实现与服务器通信 本示例以Servlet为例,演示Android与Servlet的通信. 众所周知,Android与服务器通信通常采用HTTP通信方式和Socket通信方 ...
随机推荐
- Python 安装mssql (Ubuntu)
1. Python.h:没有那个文件或目录 apt-get install python-dev 2.sqlfront.h:没有那个文件或目录 apt-get install freetds-dev
- Linux环境下实现生产者消费者问题
#include <stdio.h> #include <semaphore.h> #include <stdlib.h> #include <pthread ...
- mysql时该如何估算内存的消耗,公式如何计算?
经常有人问配置mysql时该如何估算内存的消耗.那么该使用什么公式来计算呢? 关心内存怎么使用的原因是可以理解的.如果配置mysql服务器使用太少的内存会导致性能不是最优的;如果配置了太多的内存则会导 ...
- 分布式架构高可用架构篇_08_MyCat在MySQL主从复制基础上实现读写分离
参考: 龙果学院http://www.roncoo.com/share.html?hamc=hLPG8QsaaWVOl2Z76wpJHp3JBbZZF%2Bywm5vEfPp9LbLkAjAnB%2B ...
- NBUT 1602 Mod Three(线段树单点更新区间查询)
[1602] Mod Three 时间限制: 5000 ms 内存限制: 65535 K 问题描述 Please help me to solve this problem, if so, Liang ...
- HDU 3639 Bone Collector II(01背包第K优解)
Bone Collector II Time Limit: 5000/2000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others ...
- POJ 1182 食物链(种类并查集)
食物链 Time Limit: 1000MS Memory Limit: 10000K Total Submissions: 63592 Accepted: 18670 Description ...
- 解决main No MyBatis mapper was found in 的警告
在集成Spring + mybaits时出现以下警告 org.mybatis.spring.mapper.MapperScannerConfigurer$Scanner.main No MyBatis ...
- Javascript 笔记与总结(2-18)正则验证与正则匹配
① 判断 String 是否符合正则要求 patt.test(String); [例]表单提交: a.用户名不能为空,只能是数字及字母,6-11位 b.email 不能为空且格式正确 <!DOC ...
- 一个项目软件的大小基本都占用在外部引用的jar包上了。
1.一个项目几百兆,基本都是外部jar包,引用的. 2.自己本身业务代码并没有那么多的 3.看下meven的仓库大小就知道了,都几百兆