【问题标题】:No able to download .xlsx file in jsp无法在jsp中下载.xlsx文件
【发布时间】:2020-03-21 20:48:58
【问题描述】:

我为下载文件编写了如下代码:

String filename = request.getParameter("file").toString();   
String filepath = request.getParameter("path").toString(); ;  
response.setContentType("APPLICATION/OCTET-STREAM");   
response.setHeader("Content-Disposition","attachment; filename=\"" + filename + "\"");   
FileInputStream fileInputStream=new FileInputStream(filepath + filename);         
int i;   

while ((i = fileInputStream.read()) != -1) {  
    out.write(i);
}   

fileInputStream.close();  

【问题讨论】:

  • 欢迎来到 SO!请阅读How to askHow to create a Minimal, Complete, and Verifiable 示例,然后更新您的问题。简而言之:描述你的期望和得到的,即你认为是错误的。你看到任何例外吗?你调试过代码吗?
  • 感谢您的分享。抱歉没有解释问题。

标签: java file jsp file-upload


【解决方案1】:

我在带有 scriplet 标签的 jsp 页面中使用此代码,即

现在我在 servlet 中尝试过,现在可以打开 .xlsx 文件。工作代码如下:

 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub



          String filename = request.getParameter("file").toString();   
          String filepath = request.getParameter("path").toString();  

         File f = new File (filepath + filename);
         //set the content type(can be excel/word/powerpoint etc..)

         String type = request.getParameter("type");
         response.setContentType (type);

         //set the header and also the Name by which user will be prompted to save
         response.setHeader ("Content-Disposition", "attachment; filename=\""+filename+"\"");

         //get the file name
         String name = f.getName().substring(f.getName().lastIndexOf("/") + 1, f.getName().length());

         //OPen an input stream to the file and post the file contents thru the 
         //servlet output stream to the client m/c
          InputStream in = new FileInputStream(f);

        try{
              ServletOutputStream outs = response.getOutputStream();

              int bytesRead;
              byte[] buf = new byte[4 * 1024]; // 4K buffer

              try {
                   while ((bytesRead = in.read(buf)) != -1){ 
                       outs.write(buf, 0, bytesRead);
                   }

              } catch (IOException ioe) {
                  ioe.printStackTrace(System.out);
              }


              outs.flush();
              outs.close();
              in.close(); 
        }catch(Exception e){
            e.printStackTrace();
        }
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-27
    • 2021-10-03
    • 2019-09-15
    • 1970-01-01
    • 2016-01-10
    • 2021-10-24
    • 1970-01-01
    • 2015-09-17
    相关资源
    最近更新 更多