服务端代码:
resp.setContentType("text/html;charset=UTF-8");
// 得到下载用户的名字
String name=req.getParameter("name");
//下载的所有图片
ArrayList downList=UserDbUtil.getInstance().downloadPIC(DbUtil.openDb(), name);
FileInputStream fis=null;
OutputStream toClient=null;
for (int i = 0; i < downList.size(); i++) {
System.out.println("下载图片的路径:"+downList.get(i));
// 解决中文乱码问题
String filename = new String(downList.get(i).getBytes(
"iso-8859-1"), "UTF-8");
// 创建file对象
File file = new File(filename);
// 设置response的编码方式
resp.setContentType("application/x-msdownload");
// 写明要下载的文件的大小
resp.setContentLength((int) file.length());
// 设置附加文件名
// response.setHeader("Content-Disposition","attachment;filename="+filename);
// 解决中文乱码
resp.setHeader("Content-Disposition", "attachment;filename="
+ new String(filename.getBytes("gbk"), "iso-8859-1"));
// 读出文件到i/o流
fis = new FileInputStream(file);
BufferedInputStream buReader = new BufferedInputStream(fis);
byte[] b = new byte[1024];// 相当于我们的缓存
// 从response对象中得到输出流,准备下载
toClient = resp.getOutputStream();
int num;
// 开始循环下载
while ((num = buReader.read(b)) != -1) {
// 将b中的数据写到客户端的内存
toClient.write(b, 0, num);
}
// 将写入到客户端的内存的数据,刷新到磁盘
toClient.flush();
toClient.close();
fis.close();
System.out.println("下载图片到本地。。。。");
}
android代码:
/**
* 下载图像方法
*
* @param url
* @return
*/
public static Bitmap downloadBitmap(String url) {
Bitmap bitmap = null;
HttpGet get = new HttpGet(url);// 下载地址
// 客户端对象
HttpClient client = new DefaultHttpClient();
try {
HttpResponse resp = client.execute(get);
if (resp.getStatusLine().getStatusCode() == 200) {
// 连接成功,获取下载的数据流
InputStream in = resp.getEntity().getContent();
// 将数据流转为图像并返回(注意大图处理)
bitmap = BitmapFactory.decodeStream(in);
//获取长度
in.close();// 关闭流
Log.e("nnnnnnn", "服务器下载到图片");
}
client.getConnectionManager().shutdown();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} // 执行连接获取结果
return bitmap;
}