1:读取配置文件:
filePathConfig.properties文件最好放到src目录下,因为这是从类文件加载路径,读取配置文件,在配置文件里面写上下面数组中的配置内容即可。
public static Map<String, String> getFtpConfig() {
InputStream inputStream = Util.class.getClassLoader().getResourceAsStream("filePathConfig.properties");
Properties p = new Properties();
HashMap<String, String> env = new HashMap<String, String>();
try {
p.load(inputStream);
String[] keys = new String[] { "ftphost", "ftpport", "ftpuser", "ftpassword" ,"remotepath"};
for (String key : keys) {
env.put(key, p.getProperty(key));
}
} catch (Exception e) {
}
return env;
}
2:生成新文件名:
参数str就是前台传过来的路径,如:C:/a/b/c.jpg
public static String upload(String str) throws Exception {
String newFileName = "";
if (str != null) {
String fileName = str;
if (StringUtils.isNotEmpty(fileName)) {
String suffix = "";
if (fileName.lastIndexOf(".") > 0) {
suffix = fileName.substring(fileName.lastIndexOf("."));
}
String uuid = java.util.UUID.randomUUID().toString().replaceAll("-", "");
newFileName = uuid + suffix;
}
}
return newFileName;
}
3:调用上传函数
FileInputStream in=new FileInputStream(new File(pathStr));
flag = CommonUtil.uploadFile(Util.getFtpConfig().get("ftphost"), Integer.valueOf(Util.getFtpConfig().get("ftpport")), Util.getFtpConfig().get("ftpuser"), Util.getFtpConfig().get("ftpassword"), Util.getFtpConfig().get("remotepath"), newName, in);
public static boolean uploadFile(String url,int port,String username, String password, String path, String filename, 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.enterLocalPassiveMode(); ftp.setFileType(FTP.BINARY_FILE_TYPE); ftp.storeFile(path +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; }
FileZilla Server的使用方法在网上很多,随便看一下就知道怎么用了,这里我想说的是我可能需要根据特定的条件将文件上传到不同的文件夹下,这个要怎么办?
假如说我们需要按条件分别上传文件到AA,BB,CC三个folder中,我们在配置文件中是配置一个用户guest,不可能为每一个文件夹都配置一个用户吧?我们只需要
找到AA,BB,CC三个folder的上一层目录,把这个目录设置为home directory(FTP),这样当FTP做登录连接的时候就会找到FTP这个目录,我们只需要把上面程序
中的remotepath参数分别传入/AA,/BB,/CC 就可以了。