要提供给客户一个下载xml文件备份的功能
思路确定了
生成xml
在服务器指定目录创建文件
取得文件路径,弹出下载框
Java语言:01 <%@ page contentType="text/html;charset=UTF-8" language="java"%>
02 <%@ page import="java.io.*" %>
03 <%
04 String pathurl = (String)request.getAttribute("pathurl");
05 if(pathurl !=null && !pathurl.equals("")){
06
07 String addressReport = application.getRealPath("/")+"saveFiles"+File.separator+pathurl;
08 //String addressReport = PageConstraint.XML_PATH_SEND+pathurl;
09 addressReport = addressReport.replace(File.separator,File.separator+File.separator);
10
11 // 设置响应头和下载保存的文件名
12 response.setContentType("APPLICATION/OCTET-STREAM;charset=UTF-8");
13 response.setHeader("Content-Disposition",
14 "attachment; filename=\"" + pathurl + "\"");
15
16 // 打开指定文件的流信息
17 java.io.FileInputStream fileInputStream =
18 new java.io.FileInputStream(addressReport);
19
20 写出流信息
21 int i;
22 while ((i=fileInputStream.read()) != -1) {
23 out.write(i);
24 }
25
26 fileInputStream.close();
27 out.close();
28
29 }
30 %>
这么写在jsp文件中的代码,开始试验没有问题,但是如果xml中有中文,就会是乱码,xml文件是使用utf8生成的,猜想可能是在流读取的时候编码不对,于是在网上搜得了下面这样的写法,通过InputStreamReader设置了编码UTF-8
测试成功
Java语言:
01 <%@ page contentType="text/html;charset=UTF-8" language="java"%>
02 <%@ page import="java.io.*" %>
03 <%
04 String pathurl = (String)request.getAttribute("pathurl");
05 if(pathurl !=null && !pathurl.equals("")){
06
07 String addressReport = application.getRealPath("/")+"saveFiles"+File.separator+pathurl;
08 //String addressReport = PageConstraint.XML_PATH_SEND+pathurl;
09 addressReport = addressReport.replace(File.separator,File.separator+File.separator);
10
11 // 设置响应头和下载保存的文件名
12 response.setContentType("APPLICATION/OCTET-STREAM;charset=UTF-8");
13 response.setHeader("Content-Disposition",
14 "attachment; filename=\"" + pathurl + "\"");
15
16 // 打开指定文件的流信息
17 java.io.FileInputStream fileInputStream =
18 new java.io.FileInputStream(addressReport);
19
20 // 写出流信息
21 //int i;
22 //while ((i=fileInputStream.read()) != -1) {
23 //out.write(i);
24 //}
25
26 //fileInputStream.close();
27 //out.close();
28
29 InputStreamReader reader=new InputStreamReader(fileInputStream,"UTF-8");
30 int i=0;
31 while((i=reader.read())!=-1){
32 out.write(i);
33
34 }
35 reader.close();
36 fileInputStream.close();
37 out.close();
38 }
39 %>
总结:还是对java的流相关只是掌握不清啊,不能熟练运用
没有评论:
发表评论