话不多说,直接上在项目中用到的代码。
package com.fnd.skc.view.customer;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import com.fnd.skc.entity.system.SystemSet;
import com.fnd.skc.service.system.SystemSetService;
public class ExportTemplateServlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = -5238725598277232173L;
public ExportTemplateServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String title = "导入清单模板.xls";
response.reset();//清空输出流
response.setCharacterEncoding("UTF-8");//设置编码格式
response.setContentType("application/msexcel;charset=UTF-8");//设置输出文件类型
response.setHeader("Content-disposition", "attachement;filename=" + new String(title.getBytes("gb2312"), "ISO8859-1"));
String filePath = "";
ApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext());
SystemSetService systemSetService = (SystemSetService) applicationContext.getBean(SystemSetService.class);
SystemSet systemSet = systemSetService.findSystemSet();
if(systemSet != null) {
filePath = systemSet.getTemplatePath() + File.separator + title;
File file = new File(filePath);
FileInputStream fis = new FileInputStream(file);
OutputStream os = response.getOutputStream();
copyStream(fis, os, true);
fis.close();
os.close();
}
}
/**
* 复制流 到 前端浏览器
* @param source 源文件输入流
* @param dest 输出流
* @param flush
* @return total
* @throws IOException
*/
private final long copyStream(InputStream source, OutputStream dest,
boolean flush) throws IOException {
int bytes;
long total = 0l;
byte[] buffer = new byte[2048];
while ((bytes = source.read(buffer)) != -1) {
if (bytes == 0) {
bytes = source.read();
if (bytes < 0)
break;
dest.write(bytes);
if (flush)
dest.flush();
total += bytes;
}
dest.write(buffer, 0, bytes);
if (flush)
dest.flush();
total += bytes;
}
return total;
}
}