js:
function load() { var url="http://127.0.0.1:8080/xiao/loadController.do?downloadSoft&soft=xx.exe"; url=encodeURI(url); window.location.href=url; }
java:
@RequestMapping(params="downloadSoft") public void downloadSoft(HttpServletRequest request, HttpServletResponse response){ String softName=request.getParameter("soft"); HttpSession session=request.getSession(); ServletContext application=session.getServletContext(); String filePath=application.getRealPath("/client/"+softName); try(BufferedInputStream bis=new BufferedInputStream(new FileInputStream(filePath))){ try(BufferedOutputStream bos=new BufferedOutputStream(response.getOutputStream())) { setFileDownloadHeader(request,response,softName); int byteRead=0; byte[] buffer=new byte[8192]; while((byteRead=bis.read(buffer,0,8192))!=-1){ bos.write(buffer,0,byteRead); } }catch (Exception e){ e.printStackTrace(); } }catch (Exception e){ e.printStackTrace(); } } /** * 解决中文名称 * @param request * @param response * @param fileName */ public void setFileDownloadHeader(HttpServletRequest request, HttpServletResponse response, String fileName) { try { //中文文件名支持 String encodedfileName; String agent = request.getHeader("USER-AGENT"); if (null != agent && agent.contains("MSIE")) {//IE encodedfileName = java.net.URLEncoder.encode(fileName, "UTF-8"); } else if (null != agent && agent.contains("Mozilla")) { encodedfileName = new String(fileName.getBytes("UTF-8"), "iso-8859-1"); } else { encodedfileName = java.net.URLEncoder.encode(fileName, "UTF-8"); } response.setHeader("Content-Disposition", "attachment; filename=\"" + encodedfileName + "\""); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } }