开发框架用的是bootstrap+ssm+oracle。
想实现一个功能就是点击按钮下载指定的文件。
如果先简单些,固定下载我D盘的一个文件,这个该怎么写?
jsp中加了一个按钮:
<button id="download_origin_file" class="btn btn-sm btn-danger">下载文件</button>
js中照着网上的说明加了:
window.open("file:d:\file\");
但没用,不知道这个js代码该怎么写?
然后真实环境是在linux上的,后台是已经可以取到一个服务器的文件夹path和具体文件的filefullname,应该是只要连接替换就行的吧 ?
window.open()要是一个接口的地址 不是个绝对路径 浏览器是识别不了这么写的 后端开接口 返回文件流
里面的地址应该是 http:ip:port/xx/xx 写相对路径 域名都可以
https://jingyan.baidu.com/article/afd8f4deabfe0234e286e985.html
//jsp
<button id="download_origin_file" class="btn btn-sm btn-danger" onclick="downloadFile()">下载文件</button>
function downloadFile(){
window.location.href="/xxx/xxx/downloadFile"
}
//后台
@RequestMapping(value = "/downloadFile", method = {RequestMethod.POST, RequestMethod.GET })
public void downloadFile(HttpServletRequest request,HttpServletResponse response) throws Exception{
File file = new File("这里是你文件的路径");
if(!file.exists()){
return;
}
response.setCharacterEncoding("utf-8");
try {
InputStream inputStream = new FileInputStream(file);
OutputStream os = response.getOutputStream();
byte[] b = new byte[2048];
int length;
while ((length = inputStream.read(b)) > 0) {
os.write(b, 0, length);
}
os.close();
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Jsp代码
<%
response.setContentType("application/x-download");//设置为下载application/x-download
String filedownload = "/要下载的文件名"; //即将下载的文件的相对路径
String filedisplay = "最终要显示给用户的保存文件名"; //下载文件时显示的文件保存名称
String filenamedisplay = URLEncoder.encode(filedisplay,"UTF-8");
response.addHeader("Content-Disposition","attachment;filename=" + filenamedisplay);
try{
RequestDispatcher dis = application.getRequestDispatcher(filedownload);
if(dis!= null){
dis.forward(request,response);
}
response.flushBuffer();
}catch(Exception e){
e.printStackTrace();
}finally{
}
%>
2、采用文件流输出的方式下载
Jsp代码
<%@page language="java" contentType="application/x-msdownload" pageEncoding="gb2312"%>
<%
//关于文件下载时采用文件流输出的方式处理:
//加上response.reset(),并且所有的%>后面不要换行,包括最后一个;
response.reset();//可以加也可以不加
response.setContentType("application/x-download");
//application.getRealPath("/main/mvplayer/CapSetup.msi");获取的物理路径
String filedownload = "想办法找到要提供下载的文件的物理路径+文件名";
String filedisplay = "给用户提供的下载文件名";
String filedisplay = URLEncoder.encode(filedisplay,"UTF-8");
response.addHeader("Content-Disposition","attachment;filename=" + filedisplay);
java.io.OutputStream outp = null;
java.io.FileInputStream in = null;
try {
outp = response.getOutputStream();
in = new FileInputStream(filenamedownload);
byte[] b = new byte[1024];
int i = 0;
while((i = in.read(b)) > 0) {
outp.write(b, 0, i);
}
outp.flush();
//要加以下两句话,否则会报错
//java.lang.IllegalStateException: getOutputStream() has already been called for //this response
out.clear();
out = pageContext.pushBody();
} catch(Exception e){
System.out.println("Error!");
e.printStackTrace();
}finally{
if(in != null){
in.close();
in = null;
}
//这里不能关闭
//if(outp != null) {
//outp.close();
//outp = null;
//}
}
%>