e8f4eeec915bbbfaf5ad893dc3357a0c177f2d56.svn-base 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package xin.glue.ui.common;
  2. import java.io.File;
  3. import java.io.FileInputStream;
  4. import java.io.IOException;
  5. import java.io.InputStream;
  6. import java.io.UnsupportedEncodingException;
  7. import java.net.URLDecoder;
  8. import java.net.URLEncoder;
  9. import javax.servlet.ServletException;
  10. import javax.servlet.ServletOutputStream;
  11. import javax.servlet.http.HttpServlet;
  12. import javax.servlet.http.HttpServletRequest;
  13. import javax.servlet.http.HttpServletResponse;
  14. public class ExcelDownload extends HttpServlet{
  15. private String fileName;
  16. /**
  17. *
  18. */
  19. private static final long serialVersionUID = 1L;
  20. @Override
  21. public void init() throws ServletException {
  22. super.init();
  23. fileName= this.getClass().getClassLoader().getResource("/").getPath().replaceFirst("WEB-INF/classes/", "")+"tmp/";
  24. try {
  25. fileName =URLDecoder.decode(fileName,"utf-8");
  26. } catch (UnsupportedEncodingException e) {
  27. e.printStackTrace();
  28. }
  29. File file = new File(fileName);
  30. if(!file.exists()){
  31. file.mkdirs();
  32. }
  33. }
  34. protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  35. String filepath = request.getParameter("filepath");
  36. if(filepath.indexOf(".xml")>0){
  37. filepath = filepath +XmlOutput.EXT;
  38. }
  39. String fullFilePath = fileName + filepath;
  40. /*读取文件*/
  41. File file = new File(fullFilePath);
  42. /*如果文件存在*/
  43. if (file.exists()) {
  44. String name = URLEncoder.encode(file.getName(), "utf-8");
  45. response.reset();
  46. response.setContentType("application/x-msdownload");
  47. response.addHeader("Content-Disposition", "attachment; filename=\"" + name + "\"");
  48. int fileLength = (int) file.length();
  49. response.setContentLength(fileLength);
  50. /*如果文件长度大于0*/
  51. if (fileLength != 0) {
  52. /*创建输入流*/
  53. InputStream inStream = new FileInputStream(file);
  54. byte[] buf = new byte[4096];
  55. /*创建输出流*/
  56. ServletOutputStream servletOS = response.getOutputStream();
  57. int readLength;
  58. while (((readLength = inStream.read(buf)) != -1)) {
  59. servletOS.write(buf, 0, readLength);
  60. }
  61. inStream.close();
  62. servletOS.flush();
  63. servletOS.close();
  64. }
  65. }
  66. }
  67. }