`
yjshengshe
  • 浏览: 201750 次
  • 性别: Icon_minigender_1
  • 来自: 南京
社区版块
存档分类
最新评论

利用ftpclient下载文件 ,解决window.open不能下载txt文件和中文问题

阅读更多

我现在用JavaScript的window.open('url'),其中url是ftp地址并且地址中含有中文,运行的时候不能下载该ftp地址下的文件,例如:ftp://test:test@10.32.166.144/flashfxp/激活码.txt 但是如果地址是全英文的话就能下载,另外,文件是存在aix系统上,并且系统支持中文。
希望知道是高手赐教下啊!

现在就来看下我解决的代码吧,希望对遇到同样问题的人有点帮助。

1)把ftp地址中的文件保存到本地的java类源码:

package test;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;

public class Ftp {

/**
* Description: 从FTP服务器下载文件
* @param ip FTP服务器的ip地址
* @param port FTP服务器端口,默认为:21
* @param username FTP登录账号
* @param password FTP登录密码
* @param remotePath FTP服务器上的相对路径
* @param fileName 要下载的文件名
* @param localPath 下载后保存到本地的路径
* @return
*/
public static boolean downFile(String ip, int port,String username, String password, String remotePath,String fileName,String localPath) {  
     boolean success = false;  
     FTPClient ftp = new FTPClient();  
     try {  
         int reply;  
         ftp.connect(ip, port);
         //下面三行代码必须要,而且不能改变编码格式,否则不能正确下载中文文件
         ftp.setControlEncoding("GBK");
         FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_NT);  
         conf.setServerLanguageCode("zh");
       
         //如果采用默认端口,可以使用ftp.connect(url) 的方式直接连接FTP服务器  
         ftp.login(username, password);//登录  
         reply = ftp.getReplyCode();  
         if (!FTPReply.isPositiveCompletion(reply)) {  
             ftp.disconnect();  
             return success;  
         }  
        
        
         ftp.changeWorkingDirectory(remotePath);//转移到FTP服务器目录  
         FTPFile[] fs = ftp.listFiles();  
        
         for(int i = 0; i < fs.length; i++){
         FTPFile ff = fs[i];
             if(ff.getName().equals(fileName)){  
            
                 File localFile = new File(localPath+File.separator+ff.getName());  
//                   
                 OutputStream is = new FileOutputStream(localFile);  
                
                 //注意此处retrieveFile的第一个参数由GBK转为ISO-8859-1编码。否则下载后的文件内容为空。
                 //原因可能是由于aix系统默认的编码为ISO-8859-1
                 ftp.retrieveFile(new String(ff.getName().getBytes("GBK"),"ISO-8859-1"), is);  
                 is.close();  
             }  
         }  
           
         ftp.logout();  
         success = true;  
     } catch (IOException e) {  
         e.printStackTrace();  
     } finally {  
         if (ftp.isConnected()) {  
             try {  
                 ftp.disconnect();  
             } catch (IOException ioe) {  
             }  
         }  
     }  
     return success;  
}

public static void main(String[] args) {
   // TODO Auto-generated method stub
  Ftp.downFile("10.32.166.144", 21, "test", "test", "/flashfxp", "激活码.txt", "C:");
   try {
    String string = new String("激活码".getBytes("utf-8"),"utf-8");
    System.out.println(string);
   } catch (UnsupportedEncodingException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  
}

}


2)将ftp资源以文件流的方式打开,由用户决定保存在本地何处,程序运行后可以从IE跳出框中打开或者保存的Action代码,利用Struts1写的:

/*
* Generated by MyEclipse Struts
* Template path: templates/java/JavaClass.vtl
*/
package com.mocha.test;


import java.io.IOException;

import java.io.OutputStream;

import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;


public class DownloadAction extends Action{

    /** *//**
     * Method execute
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return ActionForward
     * @throws IOException
     */
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) throws IOException{

       
        OutputStream os=null;
            try {
               
                os = response.getOutputStream();
               
                response.reset();       
               
                downFile("10.32.166.144", 21, "test", "test", "/flashfxp", "激活码.txt",os,response);
                //downFile(ip, 21,ftp_user,ftp_pwd,remotePath, filename,os,response);
              
            } catch (IOException e){
                // TODO Auto-generated catch block
                e.printStackTrace();
            }finally{
                try{
                    os.close();
                   
                } catch (IOException e){
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
               
            }
        return null;

    }
   

   
/**
* Description: 从FTP服务器下载文件
* @param ip FTP服务器ip地址
* @param port FTP服务器端口,默认为21
* @param username FTP登录账号
* @param password FTP登录密码
* @param remotePath 附件在FTP服务器上的绝对路径
* @param fileName 要下载的文件名
* @param outputStream 输出流
* @param response
* @return
*/
public static boolean downFile(String ip, int port,String username, String password, String remotePath
    ,String fileName,OutputStream outputStream,HttpServletResponse response) {  
     boolean success = false;  
     FTPClient ftp = new FTPClient();  
     try {  
         int reply;  
         ftp.connect(ip, port);
         //下面三行代码必须要,而且不能改变编码格式
         ftp.setControlEncoding("GBK");
         FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_NT);  
         conf.setServerLanguageCode("zh");
       
         //如果采用默认端口,可以使用ftp.connect(url) 的方式直接连接FTP服务器  
         ftp.login(username, password);//登录  
         reply = ftp.getReplyCode();  
         if (!FTPReply.isPositiveCompletion(reply)) {  
             ftp.disconnect();  
             return success;  
         }  
        
        
         ftp.changeWorkingDirectory(remotePath);//转移到FTP服务器目录  
         FTPFile[] fs = ftp.listFiles();  
        
         for(int i = 0; i < fs.length; i++){
         FTPFile ff = fs[i];
             if(ff.getName().equals(fileName)){
            
             String filename = fileName;
                 //这个就就是弹出下载对话框的关键代码
                 response.setHeader("Content-disposition",
                                    "attachment;filename=" +
                                    URLEncoder.encode(filename, "utf-8"));
                 //将文件保存到输出流outputStream中
                 ftp.retrieveFile(new String(ff.getName().getBytes("GBK"),"ISO-8859-1"), outputStream);
                 outputStream.flush();
                 outputStream.close();
             }  
         }  
           
         ftp.logout();  
         success = true;  
     } catch (IOException e) {  
         e.printStackTrace();  
     } finally {  
         if (ftp.isConnected()) {  
             try {  
                 ftp.disconnect();  
             } catch (IOException ioe) {  
             }  
         }  
     }  
     return success;  
}
}

差点忘了利用ftpclient要用到的jar包了,呵呵,就这两个了:commons-net-1.4.1.jar、jakarta-oro- 2.0.8.jar

对了我用的jdk是1.4的。所以commons-net-1.4.1.jar用了这个版本比较老的。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics