package com.foriseland.ec.product.controller;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
/**
*
* @author sx
* @date 2018年1月31日下午8:52:38
*/
@Slf4j
@Controller
@RequestMapping("/fileOperation")
@Api(tags="文件操作")
public class FileOperationController {
@RequestMapping("/downLoadTemplate")
public void downLoadTemplate(HttpServletRequest request,HttpServletResponse response) {
log.info("FileOperationController ..downLoadTemplate() start");
OutputStream out=null;
FileInputStream inputStream=null;
try {
//获取模板名称
String templateName=request.getParameter("templateName");
if(templateName!=null) {
if(!(templateName.endsWith(".xls")||templateName.endsWith(".xlsx"))) {
templateName=templateName+".xlsx";
}
}
//下载后本地文件名
String fileName=request.getParameter("fileName");
if(fileName==null||fileName.trim().equals("")) {
fileName=new SimpleDateFormat("yyyyMMddhhmmmss").format(new Date()).toString();
}
if(!(fileName.endsWith(".xls")||fileName.endsWith(".xlsx"))) {
fileName+=".xls";
}
//文件名的两种处理方式,防中文乱码
fileName=new String(fileName.getBytes("UTF-8"),"ISO-8859-1");
//fileName=URLEncoder.encode(fileName, "UTF-8");
//获取模板位置
String templatePath="D:\\upload";
//获取模板实际位置
String path=templatePath+File.separator+templateName;
//设置响应类型
response.setContentType("multipart/form-date");
//设置文件头
//response.setHeader("Content-Disposition", "attachment:fileName="+fileName);
/*判断用户浏览器,设置Content-Disposition.
if(request.getHeader("User-Agent").toLowerCase().indexOf("firefox")>-1) {
response.setHeader("Content-Disposition", "attachment;filename*=UTF-8''"+fileName);
System.out.println("firefox");
}else {
response.setHeader("Content-Disposition", "attachment;filename="+fileName);
}*/
//不用判断用户浏览器,设置Content-Disposition.
response.setHeader("Content-Disposition", "attachment;filename*=UTF-8''"+fileName);
response.addHeader("Content-Type", "application/vnd.ms-excel");
//获取文件对象
File file=new File(path);
inputStream=new FileInputStream(file);
//通过response获取outputstream对象
out=response.getOutputStream();
byte[] buffer=new byte[512];
int b=inputStream.read(buffer);
while(b!=-1) {
//将指定长度字节写出到输出流中
out.write(buffer, 0, b);
b=inputStream.read(buffer);
}
inputStream.close();
out.close();
out.flush();
}catch(Exception ex) {
ex.printStackTrace();
}
}
}