使用java上传到ftp服务器后将文件名存储到数据库

时间:2014-05-04 13:50:48

标签: java sql file-upload ftp

我正在开发一个将文件上传到ftp服务器的实用程序。代码运行正常。但现在我想将文件名保存到服务器端的sql数据库。请帮我解决一下这个。下面是文件上传的代码。它正在运行。

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;

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

public class FTPUploader {

    FTPClient ftp = null;

    public FTPUploader(String host, String user, String pwd) throws Exception{
        ftp = new FTPClient();
        ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));
        int reply;
        ftp.connect(host);
        reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            throw new Exception("Exception in connecting to FTP Server");
        }
        ftp.login(user, pwd);
        ftp.setFileType(FTP.BINARY_FILE_TYPE);
        ftp.enterLocalPassiveMode();
    }
    public void uploadFile(String localFileFullName, String fileName, String hostDir)
            throws Exception {
        try(InputStream input = new FileInputStream(new File(localFileFullName))){
             String       ss=hostDir+"/swaps";
                    this.ftp.makeDirectory(ss);
                     boolean changeWorkingDirectory = ftp.changeWorkingDirectory(ss);
        //this.ftp.storeFile(ss + fileName, input);
                     if(changeWorkingDirectory)
                this.ftp.storeFile(fileName, input);
        }
    }

    public void disconnect(){
        if (this.ftp.isConnected()) {
            try {
                this.ftp.logout();
                this.ftp.disconnect();
            } catch (IOException f) {
                // do nothing as file is already saved to server
            }
        }
    }
    public static void main(String[] args) throws Exception {
        System.out.println("Start");
        FTPUploader ftpUploader = new FTPUploader("www.web.com", "swaswa", "swaswa");
        //FTP server path is relative. So if FTP account HOME directory is "/home/pankaj/public_html/" and you need to upload 
        // files to "/home/pankaj/public_html/wp-content/uploads/image2/", you should pass directory parameter as "/wp-content/uploads/image2/"
        ftpUploader.uploadFile("D:\\o.jpg", "qq.jpg", "");
                ///netsh advfirewall set global StatefulFTP disable
        ftpUploader.disconnect();
        System.out.println("Done");
    }

}

0 个答案:

没有答案