有时候需要提供一些文件供用户下载,本文就写了一个支持文件下载的方法,供参考:
例子需要下载的是Excel表格,具体实现:、
封装一个下载方法,方便使用:
/**
* 下载文件
* 创建人:A-bing
* 创建时间:2018年2月2日
*/
public class FileDownload {
/**
* @param response
* @param filePath //文件完整路径(包括文件名和扩展名)
* @param fileName //下载后看到的文件名
* @return 文件名
*/
public static void fileDownload(final HttpServletResponse response, String filePath, String fileName) throws Exception{
byte[] data = FileUtil.toByteArray2(filePath);
fileName = URLEncoder.encode(fileName, "UTF-8");
response.reset();
response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
response.addHeader("Content-Length", "" + data.length);
response.setContentType("application/octet-stream;charset=UTF-8");
OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
outputStream.write(data);
outputStream.flush();
outputStream.close();
response.flushBuffer();
}
}
实现方法:
备注:demo里面的文件是放在服务器上的,本地通过页面调用下载方法的时候,下载的文件在浏览器默认的下载路径里面,自己找一找。
/*
* 调账Excel模版下载
*/
@RequestMapping("")
public void xiazaiexcel(HttpServletResponse response) throws Exception{
String filePath = "E://utilPicture//file//tiaozhangExcel.xls";
String fileName = "tiaozhang.xls";
FileDownload.fileDownload(response, filePath, fileName);
}
完了#24
PS:补上
封装的toByteArray2方法:
/**
* 读取到字节数组2
*
* @param filePath
* @return
* @throws IOException
*/
public static byte[] toByteArray2(String filePath) throws IOException {
File f = new File(filePath);
if (!f.exists()) {
throw new FileNotFoundException(filePath);
}
FileChannel channel = null;
FileInputStream fs = null;
try {
fs = new FileInputStream(f);
channel = fs.getChannel();
ByteBuffer byteBuffer = ByteBuffer.allocate((int) channel.size());
while ((channel.read(byteBuffer)) > 0) {
// do nothing
// System.out.println("reading");
}
return byteBuffer.array();
} catch (IOException e) {
e.printStackTrace();
throw e;
} finally {
try {
channel.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
fs.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}