Android 通过Base64上传图片到服务器实现实例
作者:陋室铭 时间:2021-10-09 20:46:53
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, 40, 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, 3000);
HttpConnectionParams.setSoTimeout(httpParams, 5000);
HttpResponse response = client.execute(new HttpGet(url));
HttpEntity entity = response.getEntity();
if (entity != null) {
BufferedReader reader = new BufferedReader(new InputStreamReader(
entity.getContent(), "UTF-8"), 8192);
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() > 0) {
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 = 0; i < b.length; ++i) {
if (b[i] < 0) {
// 调整异常数据
b[i] += 256;
}
}
// 生成Jpeg图片
OutputStream out = new FileOutputStream(imgFilePath);
out.write(b);
out.flush();
out.close();
return true;
} catch (Exception e) {
return false;
}
}
OK ! 如果成功上传前端会接收到true ,反之失败false。希望对大家有所帮助!
来源:http://www.cnblogs.com/cuihongyu3503319/p/5155330.html
标签:Android,Base64,上传图片
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Java编程实现判断网上邻居文件是否存在的方法
2022-12-27 09:49:46
详解Spring Bean 之间的特殊关系
2022-10-25 21:12:17
Android文本视图TextView实现聊天室效果
2022-02-15 07:31:55
![](https://img.aspxhome.com/file/2023/3/123363_0s.jpg)
C#实现简单聊天程序的方法
2022-01-02 22:31:20
java byte数组与int,long,short,byte的转换实现方法
2023-09-08 12:26:43
Unity3D Shader实现贴图切换效果
2021-07-10 00:31:20
![](https://img.aspxhome.com/file/2023/9/77229_0s.gif)
浅析C# 函数的传值与传址
2023-11-22 04:46:57
![](https://img.aspxhome.com/file/2023/0/71730_0s.png)
java并发编程工具类JUC之ArrayBlockingQueue
2023-07-04 21:02:20
SpringBoot如何实现分离资源文件并打包
2023-02-18 12:01:49
![](https://img.aspxhome.com/file/2023/1/85501_0s.png)
java中获取json的所有key方法
2023-10-15 06:15:26
C#日期转换函数分享
2021-06-30 16:48:38
C#通过属性名字符串获取、设置对象属性值操作示例
2022-01-06 14:28:08
Javassist用法详解
2023-06-26 17:11:54
使用Java开发实现OAuth安全认证的应用
2023-07-16 13:55:44
![](https://img.aspxhome.com/file/2023/7/64917_0s.png)
Java 网络爬虫基础知识入门解析
2022-05-16 02:39:06
![](https://img.aspxhome.com/file/2023/3/77473_0s.png)
C# ping网络IP 实现网络状态检测的方法
2023-01-11 14:31:05
详谈java 堆区、方法区和栈区
2023-11-23 18:35:22
c# 使用线程对串口serialPort进行收发数据(四种)
2023-06-20 13:05:48
![](https://img.aspxhome.com/file/2023/5/119585_0s.jpg)
C#实现生成mac地址与IP地址注册码的两种方法
2022-07-14 20:14:58
C# 邮件发送和接收实现代码
2021-11-23 03:32:36