1

我的 JSP 页面是

<a href="xxx.lice">xx.lice</a>

我希望用户下载文件,而不是在单击链接时打开它。

我尝试将“虱子”扩展名放在tomcat中web.xml,但什么也没发生。

<mime-mapping> 
    <extension>lic</extension> 
    <mime-type>application/lic</mime-type> 
</mime-mapping>`

我还在下面尝试了另一种方法,但什么也没发生

  function openfile(url)   {   
      var a =window.open(url,"_blank","");   
      a.document.execCommand("SaveAs");   
      a.close();   
  }

  <a href="#" onclick='openfile('xxx.lice')' />

然后我在上一页尝试在下面添加一些代码,对话框存在,但看不到其他信息,我希望人们点击<a>标签然后开始弹出“saveas”对话框。

      String url = request.getRequestURL().substring(0,request.getRequestURL().lastIndexOf("/")+1) + "upload/xxx.lice";
//            //set .lic to mime type
//            String filename = "xxx.lice";
//            String mimeType = new MimetypesFileTypeMap().getContentType(filename);
//            response.setContentType( mimeType);
//            response.setHeader( "Content-Disposition", "attachment;filename="
//                    + filename );
            request.setAttribute("message", "Upload has been done successfully!\r\n The new license file is<a href=\""+ url +"\" >xxx.lice</a>");
4

1 回答 1

2
  function openfile(url)   {   
      var a =window.open(url,"_blank","");   
  }

  <a href="#" onclick="openfile('SownloadLiceFileServlet')" />

在那个 Servlet 中

  //set .lic to mime type
  String filename = "xxx.lice";
  String mimeType = new MimetypesFileTypeMap().getContentType(filename);
  response.setContentType( mimeType);
  response.setHeader( "Content-Disposition", "attachment;filename=" + filename );
  // Read the file content as a byte array
  java.io.File liceFile = new java.io.File("[File Path]");
  byte[] fileBytes = new byte[(int)liceFile.length()];
  java.io.FileInputStream liceFileStream = new java.io.FileInputStream(liceFile);
  liceFileStream.read(fileBytes);
  liceFileStream.close();
  //Push that byte array to the browser (user).
  ServletOutputStream sos = response.getOutputStream();
  sos.write(fileBytes);
于 2013-03-09T18:06:05.350 回答