Andriod文件下载含服务器端(服务器端)一

本文继续讲解andriod网络方面问题。本文主要在Eclipse上搭建服务器端。

同上篇,本文tomcat版本7.0,servlet 3.0不需要在web.xml下注册xml文件。

本文实现的内容较简单,在服务器在磁盘上读取一个pdf(其他文件也行),返回一个流文件给客户端。

服务器端的代码如下:

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {//String pathString="F:\\作业\\基于ARM11的嵌入式系统开发方法.docx";//要下载的文件路径,本文为绝对路径String pathString="D:\\我的文档\\桌面\\新建文件夹 (3)\\新概念3\\旧版新概念英语第三册课文.pdf";InputStream inputStream=null;OutputStream outputStream=null;File file=new File(pathString);inputStream=new BufferedInputStream(new FileInputStream(file));//设置为流下载response.setContentType("application/octet-sream");//设置响应大小response.setContentLength((int) file.length());response.setHeader("Content-type", "text/html;charset=UTF-8");//这句话的意思,是告诉servlet用UTF-8转码,而不是用默认的ISO8859response.setCharacterEncoding("UTF-8");String fileName=file.getName();//浏览器下载response.addHeader("Content-Disposition", "attachment;filename="+ new String( fileName.getBytes("gb2312"), "ISO8859-1" ));outputStream=new BufferedOutputStream(response.getOutputStream());// 缓冲区大小1024byte[] s=new byte[10240];int len=0;//避免最后一次读取数据时,,不满10240b的数据被填充,造成数据不准确性while((len=inputStream.read(s))!=-1){outputStream.write(s, 0, len);}if (inputStream!=null) {inputStream.close();}response.flushBuffer();if (outputStream!=null) {outputStream.close();}}doget调用dopost方法。

为便于测试,添加了浏览器下载部分代码:

response.addHeader("Content-Disposition", "attachment;filename="+ new String( fileName.getBytes("gb2312"), "ISO8859-1" ));

直接在浏览器中输入 Ip地址:8080/Myweb/downlod.do

其中Myweb/downlod.do为本文servlet的映射地址,Ip地址:8080为tomcat地址,Myweb仍让为上次的项目文件

即可下载该文件。

今天的长相厮守,只是尽力而为而已。

Andriod文件下载含服务器端(服务器端)一

相关文章:

你感兴趣的文章:

标签云: