新人第一次在csdn这种大神云集的地方写博客,如果有什么写的不好的或者不对的 请大家轻喷,留言指出哪里有问题。
在Android开发中,总是避免不了的向服务器上传图片,我前段时间项目空闲期研究下了。就我目前直到的 ,总共有两种上传图片的方法,一种是以二进制流的形式上传,另外一种是将图片编码为Base64的字符串,直接用post提交给服务器。二进制流的形式网上太多例子了,今天就贴出来我写的base64的提交吧,如有不对,请各位大神指点。
1:既然要提交服务器,http请求肯定是少不了的,这个是闲暇时候随手写的一个http请求的方法
<span style="white-space:pre"> </span>public static String doPostJson(String url, String json) throws Exception {
HttpClient httpclient = new DefaultHttpClient();
StringBuilder result = new StringBuilder();
HttpPost httpPost = new HttpPost(url);
StringEntity stringEntity = new StringEntity(json, "UTF-8");
stringEntity.setContentEncoding("UTF-8");
stringEntity.setContentType("application/json");
httpPost.setEntity(stringEntity);
HttpResponse res = httpclient.execute(httpPost);
if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
HttpEntity entity = res.getEntity();
if (entity != null) {
InputStream inputStream = entity.getContent();
InputStreamReader inputStreamReader = new InputStreamReader(
inputStream);
BufferedReader reader = new BufferedReader(inputStreamReader);
String s;
while (((s = reader.readLine()) != null)) {
result.append(s);
}
reader.close();
}
}
if (httpclient != null) {
httpclient.getConnectionManager().shutdown();
}
return result.toString();
}
2:将目标图片转化为base64的string
<span style="white-space:pre"> </span>public String bitmaptoString(Bitmap bitmap) {
// 将Bitmap转换成字符串
String string = null;
ByteArrayOutputStream bStream = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 100, bStream);
byte[] bytes = bStream.toByteArray();
string = Base64.encodeToString(bytes, Base64.DEFAULT);
return string;
}
3:将post的需要的数据准备好
<span style="white-space:pre"> </span>Bitmap bit=BitmapFactory.decodeFile(file.getAbsolutePath());
String fileString=bitmaptoString(bit);
AddSecretReq test=new AddSecretReq();
test.setAuthorId(5);
test.setContent("在网络传输或的数据转换为中间件的类型。");
test.setPicString(fileString);
final ObjectMapper om=new ObjectMapper();<pre name="code" class="java"><span style="white-space:pre"> </span>String requestJson=om.writeValueAsString(test);//这里我是用的jackson来进行json与bean的转换
4:剩下的我想大家都直到 直接调用刚才的doPostJson(String url,String json);当然 url就是接口请求地址,json就是刚才生成的那个requestjson
那下面在来看看服务器的代码:因为你上传图片的方法要依据服务器的接收图片的方来来选择 ,如果服务器选择的是二进制流来生成图片的话 我写的东西你们可以忽略,如果是base64的那么就要进行如下的操作(我的服务器代码是基于springMVC的)
1):首先服务器接收到你的请求后做如下处理:
<span style="white-space:pre"> </span>/**注册*/
@RequestMapping("/registjson")
public @ResponseBody Object registAccount(
HttpServletRequest request) {
try {
Test test=getParam(request, Test.class);
String uheader=test.getUheader();//这个就是我们提交的转码后的图片
String name=System.currentTimeMillis()+".jpg";
String a=UploadImage.upLoadImage(uheader);
System.out.println(a);
resHeader.setResCode("0000");
} catch (Exception e) {
e.printStackTrace();
resHeader.setResCode("9999");
}
return resHeader;
}
2):将这个base64格式的string重新转为图片并写如你的图片服务器
public static String upLoadImage(String imgStr) throws Exception {// 对字节数组字符串进行Base64解码并生成图片
byte[] b = Base64Util.decode(imgStr, Base64Util.DEFAULT);
for (int i = 0; i < b.length; ++i) {
if (b[i] < 0) {// 调整异常数据
b[i] += 256;
}
}
String name = String.valueOf(System.currentTimeMillis())+".jpg";
// 生成jpeg图片
String imgFilePath = IMAGE_SERVER + File.separator + name;// 新生成的图片
OutputStream out = new FileOutputStream(imgFilePath);
out.write(b);
out.flush();
out.close();
return "http://192.168.56.1:8081/image/" + name;
}
如果想看完整的代码可以直接留言找我,如果有什么不足,也请各位看在小弟第一次发博客的份上放过小弟一马 谢了!