android客戶端從服務器端下載文件,服務端返回文件流(文件不在項目裏)

android客戶端從服務器端下載文件,服務端返回文件流


服務端 strtus:

/**
 * 文件下載 : 返回文件流
 * @param mapping
 * @param actionForm
 * @param request
 * @param response
 * @return
 * @throws Exception
 */
public ActionForward fileUpload(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) throws Exception{
logger.debug("fileUpload()");
RequestMap params = WebUtil.getQueryMap(request);
String file_key = (String)params.get("filekey", "");
if(file_key != null && !"".equals(file_key)){
NewsPaperManager service = NewsPaperManager.getInstance();
String file_path = service.getFilePath(file_key);
if(file_path != null && !"".equals(file_path)){
File file = new File(file_path);
if(file.exists()){
InputStream fis = new BufferedInputStream(new FileInputStream(file));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
// 清空response
response.reset();
// 設置response的Header
response.setHeader("Content-Type", "application/octet-stream");
response.addHeader("Content-Disposition", "attachment;filename="
+ file.getName());
response.addHeader("Content-Length", "" + file.length());
OutputStream toClient = response.getOutputStream();
toClient.write(buffer);
toClient.flush();
toClient.close();
}
}
}
return null;
}



android客戶端:

    public byte[] getImage(String path) throws Exception {
URL url = new URL("http://120.197.230.53:9902/kuchuan_api/newspaper.do?method=fileUpload&filekey=2LM7vAcHt8iFX2ABTXZT");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();//基於HTTP協議的連接對象
conn.setConnectTimeout(5000);//請求超時時間 5s
conn.setRequestMethod("GET");//請求方式
Log.i("ResponseCode", "prepare");
Log.i("ResponseCode", conn.getResponseCode()+"");
if(conn.getResponseCode() == 200){//響應碼==200 請求成功
InputStream inputStream = conn.getInputStream();//得到輸入流
Log.i("ResponseCode", inputStream.toString().length()+"");
ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
Log.i("ResponseCode", "inputStream.read(buffer) :"+inputStream.read(buffer)+"");
while((len = inputStream.read(buffer)) != -1){
arrayOutputStream.write( buffer, 0, len);
Log.i("ResponseCode", "buffer.length :"+buffer.length+"  " + len);
}
inputStream.close();
arrayOutputStream.close();
Log.i("ResponseCode", "arrayOutputStream.toByteArray().length :"+arrayOutputStream.toByteArray().length+"");
}
return null;
}
   

發佈了14 篇原創文章 · 獲贊 13 · 訪問量 16萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章