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;
}
   

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值