下载文件(server.xml-tomcat5.x) - URIEcoding=GBK

来源:互联网 发布:java虚拟机的作用 编辑:程序博客网 时间:2024/06/08 07:11

/*
 * Created on 2004-12-24
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
package com.util;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import com.jspsmart.upload.*;
import com.util.StringUtil;

/**
 * @author richard
 *
 * TODO To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
public class DownCultureFile extends HttpServlet {

 private ServletConfig config;
 /**
  *
  */
 public DownCultureFile() {
  super();
  // TODO Auto-generated constructor stub
 }
 
 public void init(ServletConfig config) throws ServletException {
  this.config = config;
 }
 
 public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

  String fileName=request.getParameter("fileName");
  PrintWriter out  = response.getWriter();
  ServletContext context = config.getServletContext() ;
  SmartUpload su = new SmartUpload();
  // 初始化
  try {
   su.initialize(config,request,response);
   su.setContentDisposition(null);
   String strFileName="//culturepic//" + fileName;
   strFileName=context.getRealPath(strFileName);
   //su.downloadFile(strFileName,"",fileName);
   su.downloadFile(strFileName,"",toUtf8String(fileName));
  } catch (Exception e){
   out.println("Unable to download the file.<br>");
   out.println("Error : " + e.toString());
  }
  su=null;
 }
 
 /*
 public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  doGet(request,response) ;
 }
 */
 
 private String toUtf8String(String s) throws UnsupportedEncodingException {
  
  StringBuffer sb = new StringBuffer();
  for (int i=0;i<s.length();i++) {
   char c = s.charAt(i);
      if (c >= 0 && c <= 255) {
       sb.append(c);
      } else {
       byte[] b;
       try {
        b = Character.toString(c).getBytes("utf-8");
       }catch (Exception ex) {
        System.out.println(ex);
        b = new byte[0];
       }
       for (int j = 0; j < b.length; j++) {
        int k = b[j];
        if (k < 0) k += 256;
         sb.append("%" + Integer.toHexString(k).toUpperCase());
       }
      }
  }
  return sb.toString();
 }

}

原创粉丝点击