欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

springMVC 文件下载

程序员文章站 2022-04-09 09:24:24
...

用到的jar包:

import org.apache.commons.io.FileUtils;  
import org.springframework.context.annotation.Scope;  
import org.springframework.http.HttpHeaders;  
import org.springframework.http.HttpStatus;  
import org.springframework.http.MediaType;  
import org.springframework.http.ResponseEntity;  
import org.springframework.stereotype.Component;  
import org.springframework.web.bind.annotation.RequestMapping;  

控制层下载方法:

@Value("${file.excelFilePath}")
private String excelFilePath; //文件路径,写在.properties后缀文件中,file.excelFilePath为key值
private final static String fileName = "Excel文件名";

@RequestMapping(value = "/dataMonitordownload")
public ResponseEntity<byte[]> dataMonitor() throws IOException {
	//
	String[] paths = new File(excelFilePath).list();
	String fileExcel = "";
	for (String path : paths) {
		if (path.equals(fileName+".xlsx") || path.equals(fileName+".xls")) {
			fileExcel = path;
			break;
		}
	}
	//文件
	File file = new File(excelFilePath + "/" + fileExcel);
	//下面开始设置HttpHeaders,使得浏览器响应下载
	HttpHeaders headers = new HttpHeaders();
	//设置响应方式
	headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
	//设置响应文件 和编码,防止乱码
	headers.setContentDispositionFormData("attachment", URLEncoder.encode(file.getName(), "UTF-8"));
	//把文件以二进制形式写回
	return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.OK);
}

前台页面方法:

function dataMonitorOperateDownload(){
	postDownload("<%=request.getContextPath()%>/fileOperate/dataMonitordownload");
}

function postDownload(URL) {
	var temp = document.createElement('form');
	temp.action = URL;
	temp.method = 'post';
	temp.style.display = 'none';
	document.body.appendChild(temp);
	temp.submit();
	return temp;
}

相关标签: 下载