Package com.adm.ctl

Source Code of com.adm.ctl.DlCtl

package com.adm.ctl;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Map;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.adm.dao.CommonDao;

/**
* Servlet implementation class DlCtl
*/
public class DlCtl extends HttpServlet {
 
  private static final long serialVersionUID = 1L;
    private String upload_dir = null;
    private CommonDao dao = null;
   
  public void init(ServletConfig config) throws ServletException {
    this.dao = (CommonDao)new ClassPathXmlApplicationContext("beans.xml").getBean("dao");
    this.upload_dir = config.getServletContext().getRealPath("/")+"upload";
  }

  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    try {
            String guid = request.getParameter("guid");
            Map<String,String> fileMap = this.dao.query("usr_upload",new String[]{"filename","title"},"guid = '"+guid+"'").getData();
            System.out.println(upload_dir+File.separator+fileMap.get("filename"));
            File file = new File(upload_dir+File.separator+fileMap.get("filename"));
            // 取得文件名。
            String title = fileMap.get("title");
            // 以流的形式下载文件。
            InputStream fis = new BufferedInputStream(new FileInputStream(file));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            // 设置response的Header
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(title.getBytes("utf-8"),"ISO-8859-1"));
            response.addHeader("Content-Length", "" + file.length());
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
  }

  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    doGet(request,response);
  }

}
TOP

Related Classes of com.adm.ctl.DlCtl

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.