| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273 |
- package xin.glue.ui.common;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.UnsupportedEncodingException;
- import java.net.URLDecoder;
- import java.net.URLEncoder;
- import javax.servlet.ServletException;
- import javax.servlet.ServletOutputStream;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- public class ExcelDownload extends HttpServlet{
- private String fileName;
- /**
- *
- */
- private static final long serialVersionUID = 1L;
-
- @Override
- public void init() throws ServletException {
- super.init();
- fileName= this.getClass().getClassLoader().getResource("/").getPath().replaceFirst("WEB-INF/classes/", "")+"tmp/";
- try {
- fileName =URLDecoder.decode(fileName,"utf-8");
- } catch (UnsupportedEncodingException e) {
- e.printStackTrace();
- }
- File file = new File(fileName);
- if(!file.exists()){
- file.mkdirs();
- }
- }
- protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- String filepath = request.getParameter("filepath");
- if(filepath.indexOf(".xml")>0){
- filepath = filepath +XmlOutput.EXT;
- }
- String fullFilePath = fileName + filepath;
- /*读取文件*/
- File file = new File(fullFilePath);
- /*如果文件存在*/
- if (file.exists()) {
- String name = URLEncoder.encode(file.getName(), "utf-8");
- response.reset();
- response.setContentType("application/x-msdownload");
- response.addHeader("Content-Disposition", "attachment; filename=\"" + name + "\"");
- int fileLength = (int) file.length();
- response.setContentLength(fileLength);
- /*如果文件长度大于0*/
- if (fileLength != 0) {
- /*创建输入流*/
- InputStream inStream = new FileInputStream(file);
- byte[] buf = new byte[4096];
- /*创建输出流*/
- ServletOutputStream servletOS = response.getOutputStream();
- int readLength;
- while (((readLength = inStream.read(buf)) != -1)) {
- servletOS.write(buf, 0, readLength);
- }
- inStream.close();
- servletOS.flush();
- servletOS.close();
- }
- }
- }
- }
|