vue實現后端文件下載到當前瀏覽器


比如現在在后端生成一個.sql文件並下載到當前瀏覽器:比如我的后端接口是localhost:8087/user/userController/exportSql,

前端地址是localhost:9095/user#。

一、前端:

<el-button @click="getSql()">導出</el-button>

var url = process.env.BASE_API
url += '/userController/exportSql?userId=' + userId
window.open(url)

注意這里url不能是/user/userController/expoerSql,因為window.open,會把/當成前端的頁面地址,而不是后端。 

二、后端:

/**
	 * 導出SQL
	 */
    @ResponseBody
	@RequestMapping("/exportSql")
	public HttpResult exportSql(String userId,HttpServletResponse response){
		try {
			
			response.reset();
		    response.setContentType("text/plain");  
	        response.addHeader("Content-Disposition",  
	                "attachment;filename=測試user.sql");
	        BufferedOutputStream buff = null;  
	        StringBuffer write = new StringBuffer();  
	        String enter = "\r\n";  
	        ServletOutputStream outSTr = null;  
	        try {  
	            outSTr = response.getOutputStream();
	            buff = new BufferedOutputStream(outSTr);  
	            //拼接SQL
	            write.append("內容為"+userId);	      
	            buff.write(write.toString().getBytes("UTF-8"));  
	            buff.flush();  
	            buff.close();  
	        } catch (Exception e) {  
	            e.printStackTrace();  
	        } finally {  
	            try {  
	                buff.close();  
	                outSTr.close();  
	            } catch (Exception e) {  
	                e.printStackTrace();  
	            }  
	        }  
	        
			return HttpResult.getSuccessInstance();
		} catch (Exception e) {
			logger.error("導出SQL:" + e.getMessage(), e);
			return HttpResult.getFailedInstance("生成SQL失敗");
		}
		
	}
}

  如果是視頻,修改為:

response.setContentType("video/mpeg4");
            response.addHeader("Content-Disposition",
                    "attachment;filename="+ossResourcesInfo.getName());  

 

如果要顯示文件大小和預計時長,加上下面這段邏輯

InputStream inputStream = urlConnection.getInputStream();
 response.setHeader("Content-Length", ""+contentLength);

  

 

原文:https://blog.csdn.net/w_t_y_y/article/details/95603361


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM