java/struts/Servlet文件下载与ftp文件上传下载

1.前端代码

使用超链接到Struts的Action或Servlet

<a target="_blank" href="ftpFileAction!downloadFile.action?transUrl=ftp://10.0.2.1/tazi/a.xml">请点击下载</a>

2.后台代码 Action或Servlet

String s1=transUrl; // transUrl是前台接受的参数,get接受的参数tomcat一律使用iso-8859-1编码

transUrl=new String(transUrl.getBytes("ISO-8859-1"),"utf-8");//程序中要使用的文件名,必须转换为gbk编码
s1=s1.substring(6);
s1=s1.substring(s1.indexOf("/"));
String filename=s1.substring(s1.lastIndexOf("/")+1);
String filepath=s1.substring(0,s1.lastIndexOf("/"));


response.setCharacterEncoding("gbk");
response.setContentType("application/octet-stream");
response.addHeader("Content-Disposition", "attachment;filename="" + new String(filename.getBytes("gbk"),"ISO-8859-1")+ """);//response文件头中定义的filename包含的中文必须是原始的ISO-8859-1编码。


boolean suc=false;
suc=downFileStream("10.0.2.1", 21,"myUser","myPwd",
filepath, filename, os);//downFileStream是一个下载ftp文件到文件流的方法
if(!suc){
response.reset();
response.setCharacterEncoding("gbk");
PrintWriter writer=new PrintWriter(os);
writer.write("指定的文件不存在!");
writer.close();
}else{
os.close();
};

 

3.ftp文件下载处理

注意这里引入的包是

org.apache.commons.net.ftp.*

  (1).下载到本地

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

public static boolean downFile(String url, // FTP服务器hostname
        int port,// FTP服务器端口
        String username, // FTP登录账号
        String password, // FTP登录密码
        String remotePath,// FTP服务器上的相对路径
        String fileName,// 要下载的文件名
        String localPath// 下载后保存到本地的路径
) {
    boolean success = false;
    FTPClient ftp = new FTPClient();
    try {
        int reply;
        ftp.connect(url, port);
        // 如果采用默认端口,可以使用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();
        boolean ftpFileExist=false;
        for (FTPFile ff : fs) {
            if (ff.getName().equals(fileName)) {
                ftpFileExist=true;
                File dir = new File(localPath);
                if(!dir.exists()){
                    dir.mkdirs();
                }
                File localFile = new File(localPath + File.separator + ff.getName());
                OutputStream is = new FileOutputStream(localFile,true);
                ftp.setBufferSize(1024);
                if(ftp.setFileType(FTP.BINARY_FILE_TYPE)){
                    ftp.retrieveFile(ff.getName(), is);
                    is.close();
                }
            }
        }
        ftp.logout();
        if(ftpFileExist){
            success = true;
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException ioe) {
            }
        }
    }
    return success;
}

  (2).下载到文件输出流 OutputStream

public static boolean downFileStream(String url, // FTP服务器hostname
        int port,// FTP服务器端口
        String username, // FTP登录账号
        String password, // FTP登录密码
        String remotePath,// FTP服务器上的相对路径
        String fileName,// 要下载的文件名
        OutputStream os
) {
    boolean success = false;
    FTPClient ftp = new FTPClient();
    try {
        int reply;
        ftp.connect(url, port);
        // 如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器
        ftp.login(username, password);// 登录
        reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            return false;
        }
        ftp.changeWorkingDirectory(remotePath);// 转移到FTP服务器目录
        FTPFile[] fs = ftp.listFiles();
        boolean ftpFileExist=false;
        for (FTPFile ff : fs) {
            String ffName=new String(ff.getName().getBytes("ISO-8859-1"),"gbk");
            if (ffName.equals(fileName)) {
                ftpFileExist=true;
                ftp.setBufferSize(1024);
                if(ftp.setFileType(FTP.BINARY_FILE_TYPE)){
                    ftp.retrieveFile(ff.getName(), os);
                }
            }
        }
        ftp.logout();
        if(ftpFileExist){
            success = true;
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException ioe) {
            }
        }
    }
    return success;
}

 4.ftp文件上传

public static boolean uploadFile(String url,// FTP服务器hostname
        int port,// FTP服务器端口
        String username, // FTP登录账号
        String password, // FTP登录密码
        String path, // FTP服务器保存目录
        String filename, // 上传到FTP服务器上的文件名
        InputStream input // 输入流
) {
    boolean success = false;
    FTPClient ftp = new FTPClient();
    try {
        int reply;
        ftp.connect(url, port);// 连接FTP服务器
        // 如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器
        ftp.login(username, password);// 登录
        reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            return success;
        }
        ftp.changeWorkingDirectory(path);
        ftp.storeFile(filename, input);

        input.close();
        ftp.logout();
        success = true;
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException ioe) {
            }
        }
    }
    return success;
}

上传时中文名处理,要转换为

ISO-8859-1编码
public static void main(String[] args) throws Exception{
        FtpUtil f= new FtpUtil();
        File file=new File("D:/测试.xml");
        InputStream isInputStream=new FileInputStream(file);
        String filename=new String("中文.xml".getBytes("gbk"),"ISO-8859-1");
        f.uploadFile("10.7.0.15", 21, "dd", "dd", "/tazi",
                filename, isInputStream);
        
    }
原文地址:https://www.cnblogs.com/tazi/p/4326042.html