用servlet写的在浏览器下载文件模板

话不多说,直接上在项目中用到的代码。

 

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;
 }

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值