1. 程式人生 > >js通過Url下載檔案

js通過Url下載檔案


我們通過iframe到後臺請求一個下載,後臺通過流返回到瀏覽器,彈出儲存視窗

js程式碼:

function (){
			var voiceUrl =baseURL+ "download";
			var iframe  = document.createElement("iframe");
			document.body.appendChild(iframe); 		
			iframe.src = voiceUrl;
			iframe.style.display = "none";
		}

java程式碼:

@RequestMapping("download")
	public void download(HttpServletRequest request , HttpServletResponse response) {
		String fileName = "E:\\wew.wav";
		String headStr = "attachment; filename=\"" + fileName + "\"";
		response.setContentType("audio/x-wav|wav");
		response.setHeader("Content-Disposition", headStr);
		File file = new File(fileName);
		FileInputStream fis;
		ServletOutputStream fos;
		try {
				fis = new FileInputStream(file);
				fos = response.getOutputStream();
				
				byte[] buf = new byte[1024 * 4];
			   int size = 0;
			   while ( (size = fis.read(buf)) != -1) {
			      fos.write(buf, 0, size);
			   }
			   fis.close();
			   fos.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
我們可以新增一個按鈕,單擊呼叫上面的方法就能彈出下載框下載了,這裡演示了下載語音檔案,同理excel,txt等也可以通過上述方式進行下載,只需要設定response返回到瀏覽器的資料型別即可。