Android 通过Base64上传图片到服务器实现实例
Android通过Base64上传图片到服务器
之前做上传图片是采用HttpServlet上传,不过用了一下Base64上传图片后,感觉比HttpServlet方便很多,大家也可以跟着尝试一下。
前台图片处理:(传Bitmap对象即可)
/**
*通过Base32将Bitmap转换成Base64字符串
*@parambit
*@return
*/
publicStringBitmap2StrByBase64(Bitmapbit){
ByteArrayOutputStreambos=newByteArrayOutputStream();
bit.compress(CompressFormat.JPEG,40,bos);//参数100表示不压缩
byte[]bytes=bos.toByteArray();
returnBase64.encodeToString(bytes,Base64.DEFAULT);
}
前台发送数据:(調用setImgByStr()方法,第一個參數imgStr为Bitmap转成Base64的字符串,第二个参数imgName为图片的名字,包含后缀名.jpg)
publicstaticStringhost="http://192.168.1.166:8080/ImageServer/";
publicstaticStringgetContent(Stringurl)throwsException{
StringBuildersb=newStringBuilder();
HttpClientclient=newDefaultHttpClient();
HttpParamshttpParams=client.getParams();
//设置网络超时参数
HttpConnectionParams.setConnectionTimeout(httpParams,3000);
HttpConnectionParams.setSoTimeout(httpParams,5000);
HttpResponseresponse=client.execute(newHttpGet(url));
HttpEntityentity=response.getEntity();
if(entity!=null){
BufferedReaderreader=newBufferedReader(newInputStreamReader(
entity.getContent(),"UTF-8"),8192);
Stringline=null;
while((line=reader.readLine())!=null){
sb.append(line+"\n");
}
reader.close();
}
returnsb.toString();
}
publicstaticHttpResponsepost(Mapparams,Stringurl){
HttpClientclient=newDefaultHttpClient();
HttpPosthttpPost=newHttpPost(url);
httpPost.addHeader("charset",HTTP.UTF_8);
httpPost.setHeader("Content-Type",
"application/x-www-form-urlencoded;charset=utf-8");
HttpResponseresponse=null;
if(params!=null&¶ms.size()>0){
ListnameValuepairs=newArrayList();
for(Stringkey:params.keySet()){
nameValuepairs.add(newBasicNameValuePair(key,(String)params
.get(key)));
}
try{
httpPost.setEntity(newUrlEncodedFormEntity(nameValuepairs,
HTTP.UTF_8));
response=client.execute(httpPost);
}catch(UnsupportedEncodingExceptione){
e.printStackTrace();
}catch(ClientProtocolExceptione){
e.printStackTrace();
}catch(IOExceptione){
e.printStackTrace();
}catch(RuntimeExceptione){
e.printStackTrace();
}
}else{
try{
response=client.execute(httpPost);
}catch(ClientProtocolExceptione){
e.printStackTrace();
}catch(IOExceptione){
e.printStackTrace();
}
}
returnresponse;
}
publicstaticObjectgetValues(Mapparams,Stringurl){
Stringtoken="";
HttpResponseresponse=post(params,url);
if(response!=null){
try{
token=EntityUtils.toString(response.getEntity());
response.removeHeaders("operator");
}catch(ParseExceptione){
e.printStackTrace();
}catch(IOExceptione){
e.printStackTrace();
}
}
returntoken;
}
publicstaticObjectsetImgByStr(StringimgStr,StringimgName){
Stringurl=host+"channel-uploadImage.action";
Mapparams=newHashMap();
params.put("imgStr",imgStr);
params.put("imgName",imgName);
returngetValues(params,url);
}
后台接收数据:
publicvoiduploadPhoto(){
//获取存储路径
HttpServletRequestrequest=ServletActionContext.getRequest();
Stringpath=ServletActionContext.getServletContext().getRealPath("/")+"upload";
Filefile=newFile(path);
if(!file.exists()){
file.mkdir();
}
StringimgPath=path+request.getParameter("imgName");
StringimgStr=request.getParameter("imgStr");
booleanflag=string2Image(imgStr,imgPath);
JacksonUtil.responseJSON(response,flag);
}
后台图片处理:
/**
*通过BASE64Decoder解码,并生成图片
*@paramimgStr解码后的string
*/
publicbooleanstring2Image(StringimgStr,StringimgFilePath){
//对字节数组字符串进行Base64解码并生成图片
if(imgStr==null)
returnfalse;
try{
//Base64解码
byte[]b=newBASE64Decoder().decodeBuffer(imgStr);
for(inti=0;i
OK!如果成功上传前端会接收到true,反之失败false。希望对大家有所帮助!