java附件上傳功能實現:java大文件上傳插件

1、問題
在項目開發過程中,遇到需要將頁面上選擇的文件上傳至FTP伺服器,遇到一些坑,比如上傳文件中文名亂碼,上傳時指定上傳目錄不能自動創建等問題。

2、FTP上傳文件工具類

public class FtpUtil {
    private String hostname = "xxx";
    private Integer port = 21 ;
    private String username = "xxx";
    private String password = "xxx";
    private FTPClient client = null;

    public String initialize() throws Exception{
        client = new FTPClient();
        client.setControlEncoding("utf-8");
        client.connect(hostname, port);
        client.login(username, password);
        int replyCode = client.getReplyCode();
        if(!FTPReply.isPositiveCompletion(replyCode))
            return "Connect ftp failed";

        return "success";
    }

    public String uploadFile(String storePath, String fileName, String uploadFile) throws Exception {
        InputStream stream = new FileInputStream(new File(uploadFile));
        client.setFileType(client.BINARY_FILE_TYPE);
        this.prepareStorePath(client, storePath);
        client.sendCommand("OPTS UTF8", "ON");
        client.storeFile(fileName, stream);
        if (client.storeFile(fileName, stream))
            return "Upload file success";

        return "Upload file failed";
    }

    private void prepareStorePath(FTPClient client, String storePath) throws Exception{
        String[] split = storePath.split("\\\\");

        for (String str : split) {
            if (StringUtils.isBlank(str))
                continue;

            if (!client.changeWorkingDirectory(str)) {
                client.makeDirectory(str);
                client.changeWorkingDirectory(str);
            }
        }
    }
}

3、Application.java測試上傳

public class Application {
    public static void main(String[] args) throws Exception {
        FtpUtil ftp = new FtpUtil();
        ftp.initialize();
        ftp.uploadFile("uploads", "W3School離線手冊2017.chm", "F:\\ToolFile\\W3School離線手冊2017.chm");
    }
}

4、文件名中文亂碼解決辦法

client.sendCommand("OPTS UTF8", "ON");

5、指定文件存儲目錄不能創建解決辦法

private void prepareStorePath(FTPClient client, String storePath) throws Exception{
    String[] split = storePath.split("\\\\");

    for (String str : split) {
        if (StringUtils.isBlank(str))
            continue;

        if (!client.changeWorkingDirectory(str)) {
            client.makeDirectory(str);
            client.changeWorkingDirectory(str);
        }
    }
}

路漫漫其修遠兮,吾將上下而求索

譯文:在追尋真理方面,前方的道路還很漫長,但我將百折不撓,不遺餘力地去追求和探索。

原創文章,作者:投稿專員,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/221599.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
投稿專員的頭像投稿專員
上一篇 2024-12-09 13:12
下一篇 2024-12-09 13:12

相關推薦

發表回復

登錄後才能評論