Android中图片的上传和下载

来源:互联网 发布:真心话大冒险交友软件 编辑:程序博客网 时间:2024/06/05 11:57

作者:余蒙


      在实现一个Android的WEB服务客户端,比如微博,论坛客户端时,经常会使用到图片的上传和下载。在这里介绍如何利用HttpClient实现图片的上传和下载功能。

1 图片上传:上传图片时,首先获得图片的路径,创建文件,并将图片转化为字节流写入到request,并发送该请求。

客户端代码:        

[java] view plaincopy
  1. <span style="font-size:16px;">    File file = new File(imageUrl);   
  2.         String httpUrl = httpDomain+"AddImageServlet"+"?gid="+gid;   
  3.         HttpPost request = new HttpPost(httpUrl);    
  4.         HttpClient httpClient = new DefaultHttpClient();  
  5.         FileEntity entity = new FileEntity(file,"binary/octet-stream");  
  6.         HttpResponse response;  
  7. try {  
  8.             request.setEntity(entity);  
  9.             entity.setContentEncoding("binary/octet-stream");  
  10.             response = httpClient.execute(request);  
  11.               
  12. //如果返回状态为200,获得返回的结果  
  13.  if(response.getStatusLine().getStatusCode()==HttpStatus.SC_OK){    
  14. ……//图片上传成功             
  15. }  
  16. }  
  17. catch(Exception e){   
  18. }  
  19. </span>  


服务器端所做的工作则是接收该字节流,写入文件中,并在服务器中相应文件夹中保存该文件,并记录该文件的路径,将图片文件路径写入到数据库中保存。

服务器端代码:


[java] view plaincopy
  1. <span style="font-size:16px;">//获得新闻id  
  2.         String gid = request.getParameter("gid");         
  3.         String filePath = getRealPath(request) + "\\userpic\\";   
  4.         //      定义上载文件的最大字节   
  5.         int MAX_SIZE = 102400 * 102400;           
  6.         //      声明文件读入类   
  7.         DataInputStream in = null;   
  8.         FileOutputStream fileOut = null;              
  9.         //      取得客户端上传的数据类型   
  10.         String contentType = request.getContentType();                
  11.         if(contentType.indexOf("binary/octet-stream") >= 0){   
  12.             //      读入上传的数据   
  13.             in = new DataInputStream(request.getInputStream());   
  14.             int formDataLength = request.getContentLength();   
  15.             //  如果图片过大  
  16.             if(formDataLength > MAX_SIZE){   
  17.                 String errormsg=("上传的文件字节数不可以超过" + MAX_SIZE);  
  18.                 out.println(errormsg);  
  19.                 return ;  
  20.             }   
  21.         //      保存上传文件的数据   
  22.         byte dataBytes[] = new byte[formDataLength];   
  23.         int byteRead = 0;   
  24.         int totalBytesRead = 0;   
  25.         //      上传的数据保存在byte数组   
  26.         while(totalBytesRead < formDataLength){   
  27.         byteRead = in.read(dataBytes,totalBytesRead,formDataLength);   
  28.         totalBytesRead += byteRead;   
  29.           }   
  30.         String fileName = filePath + gid+".png";  
  31.          //     检查上载文件的目录是否存在   
  32.         File fileDir = new File(filePath);   
  33.         if(!fileDir.exists()){   
  34.         fileDir.mkdirs();   
  35.         }  
  36.         //      创建文件的写出类   
  37.         fileOut = new FileOutputStream(fileName);   
  38.         //      保存文件的数据   
  39.         fileOut.write(dataBytes);   
  40.         fileOut.close();  
  41.           
  42.         //保存文件的路径名  
  43. ……    
  44. </span>  


2 图片下载:首先获得网络图片的图片地址,发送请求后,服务器将会返回该图片的字节流,利用BitmapFactory.decodeStream()方法将字节流转化为图片并返回。具体代码如下:


[java] view plaincopy
  1. <span style="font-size:16px;">//获得网络中的图片  
  2.     public Bitmap getGossipImage(String gid){         
  3.         String httpUrl = httpDomain+"userpic/"+gid+".png";        
  4.         Bitmap bitmap = null;            
  5.         HttpGet httpRequest = new HttpGet(httpUrl);    
  6.         //取得HttpClient 对象    
  7.         HttpClient httpclient = new DefaultHttpClient();    
  8.         try {    
  9.             //请求httpClient ,取得HttpRestponse    
  10.             HttpResponse httpResponse = httpclient.execute(httpRequest);    
  11.             if(httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK){    
  12.                 //取得相关信息 取得HttpEntiy    
  13.                 HttpEntity httpEntity = httpResponse.getEntity();    
  14.                 InputStream is = httpEntity.getContent();                   
  15.                 bitmap = BitmapFactory.decodeStream(is);    
  16.                 is.close();     
  17.             }else{    
  18.                  Toast.makeText(context, "连接失败!", Toast.LENGTH_SHORT).show();        
  19.             }     
  20.                 
  21.         } catch (ClientProtocolException e) {    
  22.             e.printStackTrace();    
  23.         } catch (IOException e) {     
  24.             e.printStackTrace();    
  25.         }      
  26.         return bitmap;  
  27.     }  
  28.   
  29. </span>  


原创粉丝点击