在實現一個Android的WEB服務用戶端,比如微博,論壇用戶端時,經常會使用到圖片的上傳和下載。在這裡介紹如何利用HttpClient實現圖片的上傳和下載功能。
1 圖片上傳:上傳圖片時,首先獲得圖片的路徑,建立檔案,並將圖片轉化為位元組流寫入到request,並發送該請求。
用戶端代碼:
[java] <span style="font-size:16px;"> File file = new File(imageUrl);
String httpUrl = httpDomain+"AddImageServlet"+"?gid="+gid;
HttpPost request = new HttpPost(httpUrl);
HttpClient httpClient = new DefaultHttpClient();
FileEntity entity = new FileEntity(file,"binary/octet-stream");
HttpResponse response;
try {
request.setEntity(entity);
entity.setContentEncoding("binary/octet-stream");
response = httpClient.execute(request);
//如果返回狀態為200,獲得返回的結果
if(response.getStatusLine().getStatusCode()==HttpStatus.SC_OK){
……//圖片上傳成功
}
}
catch(Exception e){
}
</span>
<span style="font-size:16px;"> File file = new File(imageUrl);
String httpUrl = httpDomain+"AddImageServlet"+"?gid="+gid;
HttpPost request = new HttpPost(httpUrl);
HttpClient httpClient = new DefaultHttpClient();
FileEntity entity = new FileEntity(file,"binary/octet-stream");
HttpResponse response;
try {
request.setEntity(entity);
entity.setContentEncoding("binary/octet-stream");
response = httpClient.execute(request);
//如果返回狀態為200,獲得返回的結果
if(response.getStatusLine().getStatusCode()==HttpStatus.SC_OK){
……//圖片上傳成功
}
}
catch(Exception e){
}
</span>
伺服器端所做的工作則是接收該位元組流,寫入檔案中,並在伺服器中相應檔案夾中儲存該檔案,並記錄該檔案的路徑,將圖片檔案路徑寫入到資料庫中儲存。
伺服器端代碼:
[java] <span style="font-size:16px;">//獲得新聞id
String gid = request.getParameter("gid");
String filePath = getRealPath(request) + "\\userpic\\";
// 定義上傳檔案的最大位元組
int MAX_SIZE = 102400 * 102400;
// 聲明檔案讀入類
DataInputStream in = null;
FileOutputStream fileOut = null;
// 取得用戶端上傳的資料類型
String contentType = request.getContentType();
if(contentType.indexOf("binary/octet-stream") >= 0){
// 讀入上傳的資料
in = new DataInputStream(request.getInputStream());
int formDataLength = request.getContentLength();
// 如果圖片過大
if(formDataLength > MAX_SIZE){
String errormsg=("上傳的檔案位元組數不可以超過" + MAX_SIZE);
out.println(errormsg);
return ;
}
// 儲存上傳檔案的資料
byte dataBytes[] = new byte[formDataLength];
int byteRead = 0;
int totalBytesRead = 0;
// 上傳的資料儲存在byte數組
while(totalBytesRead < formDataLength){
byteRead = in.read(dataBytes,totalBytesRead,formDataLength);
totalBytesRead += byteRead;
}
String fileName = filePath + gid+".png";
// 檢查上傳檔案的目錄是否存在
File fileDir = new File(filePath);
if(!fileDir.exists()){
fileDir.mkdirs();
}
// 建立檔案的寫出類
fileOut = new FileOutputStream(fileName);
// 儲存檔案的資料
fileOut.write(dataBytes);
fileOut.close();
//儲存檔案的路徑名
……
</span>
<span style="font-size:16px;">//獲得新聞id
String gid = request.getParameter("gid");
String filePath = getRealPath(request) + "\\userpic\\";
// 定義上傳檔案的最大位元組
int MAX_SIZE = 102400 * 102400;
// 聲明檔案讀入類
DataInputStream in = null;
FileOutputStream fileOut = null;
// 取得用戶端上傳的資料類型
String contentType = request.getContentType();
if(contentType.indexOf("binary/octet-stream") >= 0){
// 讀入上傳的資料
in = new DataInputStream(request.getInputStream());
int formDataLength = request.getContentLength();
// 如果圖片過大 www.2cto.com
if(formDataLength > MAX_SIZE){
String errormsg=("上傳的檔案位元組數不可以超過" + MAX_SIZE);
out.println(errormsg);
return ;
}
// 儲存上傳檔案的資料
byte dataBytes[] = new byte[formDataLength];
int byteRead = 0;
int totalBytesRead = 0;
// 上傳的資料儲存在byte數組
while(totalBytesRead < formDataLength){
byteRead = in.read(dataBytes,totalBytesRead,formDataLength);
totalBytesRead += byteRead;
}
String fileName = filePath + gid+".png";
// 檢查上傳檔案的目錄是否存在
File fileDir = new File(filePath);
if(!fileDir.exists()){
fileDir.mkdirs();
}
// 建立檔案的寫出類
fileOut = new FileOutputStream(fileName);
// 儲存檔案的資料
fileOut.write(dataBytes);
fileOut.close();
//儲存檔案的路徑名
……
</span>
2 圖片下載:首先獲得網狀圖片的圖片地址,發送請求後,伺服器將會返回該圖片的位元組流,利用BitmapFactory.decodeStream()方法將位元組流轉化為圖片並返回。具體代碼如下:
[java] <span style="font-size:16px;">//獲得網路中的圖片
public Bitmap getGossipImage(String gid){
String httpUrl = httpDomain+"userpic/"+gid+".png";
Bitmap bitmap = null;
HttpGet httpRequest = new HttpGet(httpUrl);
//取得HttpClient 對象
HttpClient httpclient = new DefaultHttpClient();
try {
//請求httpClient ,取得HttpRestponse
HttpResponse httpResponse = httpclient.execute(httpRequest);
if(httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
//取得相關資訊 取得HttpEntiy
HttpEntity httpEntity = httpResponse.getEntity();
InputStream is = httpEntity.getContent();
bitmap = BitmapFactory.decodeStream(is);
is.close();
}else{
Toast.makeText(context, "串連失敗!", Toast.LENGTH_SHORT).show();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return bitmap;
}
</span>
<span style="font-size:16px;">//獲得網路中的圖片
public Bitmap getGossipImage(String gid){
String httpUrl = httpDomain+"userpic/"+gid+".png";
Bitmap bitmap = null;
HttpGet httpRequest = new HttpGet(httpUrl);
//取得HttpClient 對象
HttpClient httpclient = new DefaultHttpClient();
try {
//請求httpClient ,取得HttpRestponse
HttpResponse httpResponse = httpclient.execute(httpRequest);
if(httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
//取得相關資訊 取得HttpEntiy
HttpEntity httpEntity = httpResponse.getEntity();
InputStream is = httpEntity.getContent();
bitmap = BitmapFactory.decodeStream(is);
is.close();
}else{
Toast.makeText(context, "串連失敗!", Toast.LENGTH_SHORT).show();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return bitmap;
}
</span>
摘自 北京大學-Google Android實驗室