java大文件上传插件(java附件上传功能实现)

1、问题在项目开发过程中,遇到需要将页面上选择的文件上传至FTP服务器,遇到一些坑,比如上传文件中文名乱码,上传时指定上传目录不能自动创建等问题,接下来我们就来聊聊关于java大文件上传插件?以下内容大家不妨参考一二希望能帮到您!

java大文件上传插件(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);        }    }}

路漫漫其修远兮,吾将上下而求索

译文:在追寻真理方面,前方的道路还很漫长,但我将百折不挠,不遗余力地去追求和探索。

免责声明:本文仅代表文章作者的个人观点,与本站无关。其原创性、真实性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容文字的真实性、完整性和原创性本站不作任何保证或承诺,请读者仅作参考,并自行核实相关内容。文章投诉邮箱:anhduc.ph@yahoo.com

    分享
    投诉
    首页