JQuery调用Servlet实现文件下载

jsp页面上的txt附件,点击后浏览器默认直接打开,结果是乱码。

因为用户上传的txt文件可能是ANSI、Unicode、UTF-8编码的任意一种,上传时后台获取文件内容重写一遍保证浏览器打开正常太过麻烦,

同时也觉得下载到本地更为合适,所以希望实现点击下载。

最初的实现方式是在Web.xml中配置mime-type,如下:

<mime-mapping> 
<extension>txt</extension> 
<mime-type>application/txt</mime-type>
</mime-mapping>

但是最后发现在IE6上无效,仍然是直接打开,只好寻求新的方法。最后使用如题的方式解决,参考了

http://www.cnblogs.com/sydeveloper/archive/2013/05/14/3078295.html这里的文章。

代码如下:

页面js:

function downFile(filePath){
var form=$("<form>");//定义一个form表单
form.attr("style","display:none");
form.attr("target","");
form.attr("method","post");
form.attr("action","down");
var input1=$("<input>");
input1.attr("type","hidden");
input1.attr("name","filePath");
input1.attr("value",filePath);
$("body").append(form);//将表单放置在web中
form.append(input1);
form.submit();//表单提交 
form.remove();
}

js方法的调用自然不用我说了。

servlet代码如下:

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

String filePath = request.getParameter("filePath");
String fileName = ""; // 文件名,输出到用户的下载对话框
int index = 0;
if(filePath!=null && !"".equals(filePath)){
index = filePath.lastIndexOf("/");
if(index>=0){
fileName = filePath.substring(index+1, filePath.length());
}
}
// 打开指定文件的流信息
java.io.FileInputStream fs = null;
try {
String path = new FileUtil().getRootPath() + "/";
path = path + filePath;
fs = new FileInputStream(new File(path));

// 设置响应头和保存文件名
response.setContentType("APPLICATION/OCTET-STREAM");
response.setHeader("Content-Disposition", "attachment; filename=\""
+ fileName + "\"");
// 写出流信息
int b = 0;

PrintWriter out = response.getWriter();
while ((b = fs.read()) != -1) {
out.write(b);
}
fs.close();
out.close();
System.out.println("文件下载完毕.");
} catch (Exception e) {
e.printStackTrace();
System.out.println("下载文件失败!");
}

}

public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

doGet(request, response);
}

其中FileUtil().getRootPath()是获取WebRoot路径的函数。如下:

public String getRootPath() {
String strClassName = getClass().getName();
String strPackageName = "";
if (getClass().getPackage() != null) {
strPackageName = getClass().getPackage().getName();
}

String strClassFileName = "";
if (!strPackageName.equals("")) {
strClassFileName = strClassName.substring(
strPackageName.length() + 1, strClassName.length());
} else {
strClassFileName = strClassName;
}

URL url = null;
url = getClass().getResource(strClassFileName + ".class");
String strURL = url.toString();
strURL = strURL.replaceAll("file:", "");
strURL = strURL.substring(0, strURL.indexOf("/WEB-INF/"));
return strURL;
}

最后一步,别忘了在web.xml中配置servelt

<servlet>
<servlet-name>DownFile</servlet-name>
<servlet-class>com.XX.DownFileServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DownFile</servlet-name>
<url-pattern>/down</url-pattern>
</servlet-mapping>

至此,大功告成。

上一篇:js代码实现下拉菜单


下一篇:新闻编辑室第一季/全集The Newsroom迅雷下载