(测试可用)JSP 页面通过 ajax 导出附件(下载文件)实际

在前端不能真的以 ajax 去请求,而是应该用隐藏的 form 去实现

1. 前端 

function downloadFile() {

      var form = $("<form>");
      form.attr("style","display:none");
      form.attr("target","");
      form.attr("method","POST");
      form.attr("method","tts/download");

      var input1 = $("input");
      input1.attr("type","hidden");
      input1.attr("name","n1");
      input1.attr("value","v1");

      var input2 = $("input");
      input2.attr("type","hidden");
      input2.attr("name","n2");
      input2.attr("value","v2");
 
      $("body").append("input");
      form.append(input1);
      form.append(input2);

      form.submit();
      form.remove();


}

2. 服务端 java

public void download() {
    
        FileInputStream fis = null;
        ServletOutputStream sos = null;
		
        System.out.println("get here ----download...");
	try {
		HttpServletResponse res = getResponse();
		res.setHeader("Content-Disposition", "attachment;filename=test_download.wav");
		res.setContentType("application/octet-stream");
		res.setContentType("application/OCTET-STREAM;charset=UTF-8");
			
		byte b[] = new byte[1024*1024];
			
		int read = 0;
		String fn = PathKit.getWebRootPath() + "/voices/test.wav";
		fis = new FileInputStream(new File(fn));
			
		sos = res.getOutputStream();
			
		while((read=fis.read(b))!=1) {
				
		sos.write(b, 0, read);
				
		}
	}catch(Exception e) {
		e.printStackTrace();
	}finally {
			
		try{
			if(sos!=null) {
				sos.close();
			}
			if(fis!=null) {
				fis.close();
			}
		}catch(IOException e) {
			throw new RuntimeException("没有文件");
		}
			
			
	}
}

猜你喜欢

转载自hwzyyx.iteye.com/blog/2290206