java大文件上传插件(java附件上传功能实现)
程序员文章站
2023-11-24 11:28:22
1、问题在项目开发过程中,遇到需要将页面上选择的文件上传至ftp服务器,遇到一些坑,比如上传文件中文名乱码,上传时指定上传目录不能自动创建等问题。2、ftp上传文件工具类public class ft...
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);
}
}
}
路漫漫其修远兮,吾将上下而求索
译文:在追寻真理方面,前方的道路还很漫长,但我将百折不挠,不遗余力地去追求和探索。