溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

web導出文件核心代碼實例

發(fā)布時間:2021-06-30 15:28:44 來源:億速云 閱讀:138 作者:chen 欄目:大數(shù)據(jù)

本篇內(nèi)容主要講解“web導出文件核心代碼實例”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學習“web導出文件核心代碼實例”吧!

前端代碼

1.可直接寫:location.href = "后臺請求地址"
2.用XMLHttpRequest形式(ajax axios fetch):

axios({
    url: url,
    params: parameter,
    method:'get' ,
    responseType: 'blob'
  }).then(data=>{
	if (!data) {
		alert("文件下載失敗")
		return
	}
	if (typeof window.navigator.msSaveBlob !== 'undefined') {
		//處理IE
		window.navigator.msSaveBlob(new Blob([data]), fileName+'.xls')
	}else{
		let url = window.URL.createObjectURL(new Blob([data]))
		let link = document.createElement('a')
		link.style.display = 'none'
		link.href = url
		link.setAttribute('download', fileName+'.xls')
		document.body.appendChild(link)
		link.click()
		document.body.removeChild(link); //下載完成移除元素
		window.URL.revokeObjectURL(url); //釋放掉blob對象
	}
})

后臺代碼

	//從服務器上下載文件核心代碼
	response.setContentType("application/x-msdownload;charset=utf-8");
	String fileName="中文文件名.xls";
	String userAgent = request.getHeader("user-agent").toLowerCase();
	if (userAgent.contains("msie") || userAgent.contains("like gecko") ) {
		fileName = URLEncoder.encode(fileName, "UTF-8");
	}else {  
		fileName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");  
	} 
	response.setHeader("Content-disposition", "attachment; filename="+ fileName);
	
	InputStream inputStream = null;
	OutputStream outputStream=null;
	try {
		String imgurl = "服務器上的文件實際地址";
		inputStream = new BufferedInputStream(new FileInputStream(imgurl));
		outputStream = response.getOutputStream();
		byte[] buf = new byte[1024];
	    int len;
	    while ((len = inputStream.read(buf)) > 0) {
	    	outputStream.write(buf, 0, len);
	    }
	    response.flushBuffer();
	} catch (Exception e) {
		logger.info("--通過流的方式獲取文件異常--"+e.getMessage());
	}finally{
		if(inputStream!=null){
			inputStream.close();
		}
		if(outputStream!=null){
			outputStream.close();
		}
	}
	//導出excel
	
	//此處省略 生成workbook的代碼
	
	String fileName = "登記發(fā)證統(tǒng)計.xls";
	String userAgent = req.getHeader("user-agent").toLowerCase();
	if (userAgent.contains("msie") || userAgent.contains("like gecko") ) {
		fileName = URLEncoder.encode(fileName, "UTF-8");
	}else {  
		fileName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");  
	} 
	// 設置強制下載不打開           
	resp.setContentType("application/force-download"); 
	resp.setHeader("Content-disposition", "attachment; filename="+ fileName);
	OutputStream out = resp.getOutputStream();
	workbook.write(out);  
	resp.flushBuffer();

生成workbook的示例

到此,相信大家對“web導出文件核心代碼實例”有了更深的了解,不妨來實際操作一番吧!這里是億速云網(wǎng)站,更多相關(guān)內(nèi)容可以進入相關(guān)頻道進行查詢,關(guān)注我們,繼續(xù)學習!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

web
AI