开发过程中需要实现文件下载,代码如下
public void downLoadFiles(HttpServletRequest request,
HttpServletResponse response) throws Exception {
String fileName = request.getParameter("fileName");
response.setContentType("application/OCTET-STREAM;charset=UTF-8");
String path = "E:\\file";
response.setHeader("Content-Dispositon", "attachment;filename="
+ URLEncoder.encode(fileName, "utf-8"));
File file = new File(path, fileName);
FileInputStream fis = null;
BufferedOutputStream bos = null;
try {
fis = new FileInputStream(file);
bos = new BufferedOutputStream(response.getOutputStream());
byte[] buffer = new byte[1024];
int len;
while ((len = fis.read(buffer)) != -1) {
bos.write(buffer, 0, len);
bos.flush();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
fis.close();
bos.close();
}
}
上面的代码可以实现文件的下载,但是不管是用ie自带的下载器还是用迅雷其他的下载器,下载的文件名是url中的一部分,比如我们的url为/platform/createFile.do?actionType=XXX...下载中显示的文件名称为createFile.do,没有找到解决办法。故用jspsmart代替实现。代码如下:
<%@ page contentType="text/html;charset=UTF-8"
import="com.jspsmart.upload.*"
import="java.io.*" %><%
response.reset();
SmartUpload su = new SmartUpload();
su.initialize(pageContext);
su.setContentDisposition(null);
String fileName = request.getParameter("fileName");
su.downloadFile("/u02/soft/PlatformDataCheck/"+fileName);
%>
注意,除<% %>之外不要有空格和回车。