jsp实现文件下载

第一种情况:已经知道文件在服务器上的具体地址,那直接把这个地址返回给前台,把值塞到href里:
<a href="地址" id="file" target="_blank"><button type="button" id="downLoadBtn">下载</button></a>  
$("#file").attr('href',地址);//把地址塞进去,点击下载按钮的时候会直接下载,或者访问文件</span>  
或者不设置按钮,直接在回调函数成功后load:window.location.href="地址";

第二种情况:要先生成文件,然后在把文件以流的形式返回,页面会判断处理来下载;
那就要先生成一个临时路径及文件:
File temp = File.createTempFile("fileName", ".xlsx");
absolutePath = temp.getAbsolutePath();//获取的是绝对路径
再往这个文件中写内容,这个就不说了,因人而异,我是生成的excel文件,可以参考我之前的博客http://blog.csdn.net/qq_33142257/article/details/52412385
FileOutputStream outputStream = new FileOutputStream(absolutePath);//只要把其中的路径换成这个绝对路径
File file = new File(absolutePath);//这边也是
这样一来文件已经生成好了,页写入内容了,然后把这个文件名和绝对路径存入session:
import javax.servlet.http.HttpSession;  
@RequestMapping("/download")  
    @ResponseBody  
    public ApiResponse downLoad(@RequestParam(value = "ids[]", required = false)String[] ids,@RequestParam(value = "suiteIds[]", required = false)String[] suiteIds,HttpSession session){  
        FileInfo  file = testCaseProductService.downLoad(ids,suiteIds);//上面的那些操作我都放在service中处理了,然后返回了文件名和路径,封装在我定义的<span style="font-family: Arial, Helvetica, sans-serif;">FileInfo  这个model中</span>  
                session.setAttribute("path", file.getPath());//把文件名和路径存入session中  
                session.setAttribute("name", file.getName());  
                return new ApiResponse(200, "success", "");//这边起始不要要renturn什么,主要是返回后执行回调函数  
}  
返回到页面的回调函数中:
$.post("/testcaseproduct/download", { "ids": ids ,"suiteIds":suiteIds}, function(response){  
         
         window.location.href="/testcaseproduct/NewFile";//再去访问下载文件的jsp  
  });
NewFile.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8"  
    pageEncoding="UTF-8"%>  
<%@ page import="java.net.URLEncoder"%>  
<%@ page import="java.io.*"%>  
<%@ page import="javax.servlet.http.HttpSession"%>  
<%  
      
    response.reset();//可以加也可以不加    
    response.setContentType("application/octet-stream");  
    System.out.println(session.getAttribute("path"));  
  
    String filedownload = (String)session.getAttribute("path");//取之前存入的session  
    String filedisplay = (String)session.getAttribute("name")+".xlsx";  
    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(filedownload);  
  
        byte[] b = new byte[1024];  
        int i = 0;  
  
        while ((i = in.read(b)) > 0) {  
            outp.write(b, 0, i);  
        }  
        //      
        outp.flush();  
        out.clear();  
        out = pageContext.pushBody();  
    } catch (Exception e) {  
        System.out.println("Error!");  
        e.printStackTrace();  
    } finally {  
        if (in != null) {  
            in.close();  
            in = null;  
        }  
    }  
%>  

这个是行的通的,可以直接拿这个jsp测试,随便在本机找个文件,把文件名和路径放进去,直接访问这个jsp,浏览器就会下载这个文件,但是在项目中却不下载,f12会发现出现这行:
 Resource interpreted as Document but transferred with MIME type application/octet-stream: "http://localhost:8090/testcaseproduct/NewFile".这是由于chrome问题,不允许访问本地的文件,如果你复制里面的连接http://localhost:8090/testcaseproduct/NewFile,打开一个新的浏览器窗口,把链接粘进去,回车就会有文件下载,那样就是成功的,这个问题不用处理,当项目发布到服务器上时就不会出现这个问题了;因为用户在登录系统点击下载时,文件是生成在服务器中的,而下载到的是用户的电脑上的;
这个jsp的作用就是读取服务器上的文件,然后以流的形式读取,通过response返回给页面,页面会识别这个流,通过这个response.setContentType("application/octet-stream");设定的格式,来下载生成这个文件

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要使用JSP实现本地文件下载,可以按照以下步骤进行操作: 1. 在JSP页面上,创建一个下载链接或按钮,用于触发文件下载操作。例如: ```html <a href="download.jsp?filename=filename.txt">Download File</a> ``` 2. 创建一个名为download.jspJSP页面,用于处理文件下载请求。在该页面中,可以使用以下代码来实现文件下载: ```jsp <% String filename = request.getParameter("filename"); String filePath = "path/to/files/" + filename; // 指定文件的路径 File file = new File(filePath); if (file.exists()) { response.setContentType("application/octet-stream"); response.setContentLength((int) file.length()); response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\""); try (InputStream inputStream = new FileInputStream(file); OutputStream outputStream = response.getOutputStream()) { byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } } } else { // 文件不存在的处理逻辑 // 可以输出错误信息或者重定向到其他页面 } %> ``` 在上述代码中,我们首先获取请求参数中的文件名,然后构建文件的完整路径。接下来,我们检查文件是否存在,如果存在,则设置响应的Content-Type和Content-Disposition头信息。然后,使用InputStream读取文件内容,并使用OutputStream将文件内容写入响应输出流中。 请注意,在上述代码中,我们将文件路径设置为`path/to/files/`,你需要根据你的实际情况修改为正确的文件路径。 这样,当用户点击下载链接时,会触发download.jsp页面的执行,从而下载指定的文件到用户的本地计算机上。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值