Android编程实现图片的上传和下载功能示例
本文实例讲述了Android编程实现图片的上传和下载功能。分享给大家供大家参考,具体如下:
在实现一个Android的WEB服务客户端,比如微博,论坛客户端时,经常会使用到图片的上传和下载。在这里介绍如何利用HttpClient实现图片的上传和下载功能。
1图片上传:上传图片时,首先获得图片的路径,创建文件,并将图片转化为字节流写入到request,并发送该请求。
客户端代码:
Filefile=newFile(imageUrl);
StringhttpUrl=httpDomain+"AddImageServlet"+"?gid="+gid;
HttpPostrequest=newHttpPost(httpUrl);
HttpClienthttpClient=newDefaultHttpClient();
FileEntityentity=newFileEntity(file,"binary/octet-stream");
HttpResponseresponse;
try{
request.setEntity(entity);
entity.setContentEncoding("binary/octet-stream");
response=httpClient.execute(request);
//如果返回状态为200,获得返回的结果
if(response.getStatusLine().getStatusCode()==HttpStatus.SC_OK){
……//图片上传成功
}
}
catch(Exceptione){
}
服务器端所做的工作则是接收该字节流,写入文件中,并在服务器中相应文件夹中保存该文件,并记录该文件的路径,将图片文件路径写入到数据库中保存。
服务器端代码:
//获得新闻id
Stringgid=request.getParameter("gid");
StringfilePath=getRealPath(request)+"\\userpic\\";
//定义上载文件的最大字节
intMAX_SIZE=102400*102400;
//声明文件读入类
DataInputStreamin=null;
FileOutputStreamfileOut=null;
//取得客户端上传的数据类型
StringcontentType=request.getContentType();
if(contentType.indexOf("binary/octet-stream")>=0){
//读入上传的数据
in=newDataInputStream(request.getInputStream());
intformDataLength=request.getContentLength();
//如果图片过大
if(formDataLength>MAX_SIZE){
Stringerrormsg=("上传的文件字节数不可以超过"+MAX_SIZE);
out.println(errormsg);
return;
}
//保存上传文件的数据
bytedataBytes[]=newbyte[formDataLength];
intbyteRead=0;
inttotalBytesRead=0;
//上传的数据保存在byte数组
while(totalBytesRead<formDataLength){
byteRead=in.read(dataBytes,totalBytesRead,formDataLength);
totalBytesRead+=byteRead;
}
StringfileName=filePath+gid+".png";
//检查上载文件的目录是否存在
FilefileDir=newFile(filePath);
if(!fileDir.exists()){
fileDir.mkdirs();
}
//创建文件的写出类
fileOut=newFileOutputStream(fileName);
//保存文件的数据
fileOut.write(dataBytes);
fileOut.close();
//保存文件的路径名
……
2图片下载:首先获得网络图片的图片地址,发送请求后,服务器将会返回该图片的字节流,利用BitmapFactory.decodeStream()方法将字节流转化为图片并返回。具体代码如下:
//获得网络中的图片
publicBitmapgetGossipImage(Stringgid){
StringhttpUrl=httpDomain+"userpic/"+gid+".png";
Bitmapbitmap=null;
HttpGethttpRequest=newHttpGet(httpUrl);
//取得HttpClient对象
HttpClienthttpclient=newDefaultHttpClient();
try{
//请求httpClient,取得HttpRestponse
HttpResponsehttpResponse=httpclient.execute(httpRequest);
if(httpResponse.getStatusLine().getStatusCode()==HttpStatus.SC_OK){
//取得相关信息取得HttpEntiy
HttpEntityhttpEntity=httpResponse.getEntity();
InputStreamis=httpEntity.getContent();
bitmap=BitmapFactory.decodeStream(is);
is.close();
}else{
Toast.makeText(context,"连接失败!",Toast.LENGTH_SHORT).show();
}
}catch(ClientProtocolExceptione){
e.printStackTrace();
}catch(IOExceptione){
e.printStackTrace();
}
returnbitmap;
}
更多关于Android相关内容感兴趣的读者可查看本站专题:《Android图形与图像处理技巧总结》、《Android开发入门与进阶教程》、《Android调试技巧与常见问题解决方法汇总》、《Android多媒体操作技巧汇总(音频,视频,录音等)》、《Android基本组件用法总结》、《Android视图View技巧总结》、《Android布局layout技巧总结》及《Android控件用法总结》
希望本文所述对大家Android程序设计有所帮助。