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 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 namevaluepairs = new arraylist();
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 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 params = new hashmap();
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。希望对大家有所帮助!