GVKun编程网logo

使用Python脚本将文件夹从本地系统上传到FTP(python本地文件上传到服务器)

17

对于使用Python脚本将文件夹从本地系统上传到FTP感兴趣的读者,本文将会是一篇不错的选择,我们将详细介绍python本地文件上传到服务器,并为您提供关于Ajax将文件从浏览器上传到FTP服务器、j

对于使用Python脚本将文件夹从本地系统上传到FTP感兴趣的读者,本文将会是一篇不错的选择,我们将详细介绍python本地文件上传到服务器,并为您提供关于Ajax将文件从浏览器上传到FTP服务器、java实现将文件上传到ftp服务器的方法、Java将文件上传到ftp服务器、Python--文件上传到FTP服务器-- ftplib 模块的有用信息。

本文目录一览:

使用Python脚本将文件夹从本地系统上传到FTP(python本地文件上传到服务器)

使用Python脚本将文件夹从本地系统上传到FTP(python本地文件上传到服务器)

我必须使用Python脚本自动将文件夹上传到FTP。我可以上传单个文件,但不能上传包含子文件夹和文件的文件夹。我做了很多搜索,但是失败了。有人可以帮我吗?提前致谢。

#! /usr/bin/pythonimport ftplibs = ftplib.FTP(''serverip'',''usrname'',''password'') file = ''/home/rock/test.txt''ftppath = ''/IT''filename = "rak"s.cwd(ftppath)f = open(file,''rb'')                s.storbinary(''STOR '' + filename, f)f.close()                                s.quit()

答案1

小编典典

基本上,您需要使用os.walk()来获取这些文件并进行传输。

这是我为自己编写的脚本,可以完成您的大部分要求。我是很久以前写的,所以如果我再次写它,我可能会做不同的事情,但是我从中得到了很多利用。

它导入psftplib,这是我为腻子sftp编写的包装器。随意删除这些引用,或在以下位置获取该库:http
:
//code.google.com/p/psftplib/source/browse/trunk/psftplib.py

# -*- coding: utf8 -*-''''''This tool will ftp all the files in a given directory to a given locationif the file ftpallcfg.py exists in the directory it will be loaded and the values within it used, with the current directory used as the source directory.ftpallcfg.py file contains the following variables.===========================server = <server to ftp to>username = <Username for access to given server>remote_dir = <remote server directory>encrypt= True/Falsemonitor = True/Falsewalk = True/False=========================== ''''''import ftplibimport osimport getpassimport sysimport timeimport socketimport psftplib__revision__ = 1.11SLEEP_SECONDS = 1class FtpAddOns():    PATH_CACHE = []    def __init__(self, ftp_h):        self.ftp_h = ftp_h    def ftp_exists(self, path):        ''''''path exists check function for ftp handler''''''        exists = None        if path not in self.PATH_CACHE:            try:                self.ftp_h.cwd(path)                exists = True                self.PATH_CACHE.append(path)            except ftplib.error_perm, e:                if str(e.args).count(''550''):                        exists = False        else:            exists = True        return exists    def ftp_mkdirs(self, path, sep=''/''):        ''''''mkdirs function for ftp handler''''''        split_path = path.split(sep)        new_dir = ''''        for server_dir in split_path:            if server_dir:                new_dir += sep + server_dir                if not self.ftp_exists(new_dir):                    try:                        print ''Attempting to create directory (%s) ...'' % (new_dir),                        self.ftp_h.mkd(new_dir)                        print ''Done!''                    except Exception, e:                        print ''ERROR -- %s'' % (str(e.args))def _get_local_files(local_dir, walk=False):    ''''''Retrieve local files list    result_list == a list of dictionaries with path and mtime keys. ex: {''path'':<filepath>,''mtime'':<file last modified time>}    ignore_dirs == a list of directories to ignore, should not include the base_dir.    ignore_files == a list of files to ignore.    ignore_file_ext == a list of extentions to ignore.     ''''''     result_list = []    ignore_dirs = [''CVS'', ''.svn'']    ignore_files = [''.project'', ''.pydevproject'']    ignore_file_ext = [''.pyc'']    base_dir = os.path.abspath(local_dir)    for current_dir, dirs, files in os.walk(base_dir):        for this_dir in ignore_dirs:            if this_dir in dirs:                dirs.remove(this_dir)        sub_dir = current_dir.replace(base_dir, '''')        if not walk and sub_dir:            break        for this_file in files:            if this_file not in ignore_files and os.path.splitext(this_file)[-1].lower() not in ignore_file_ext:                filepath = os.path.join(current_dir, this_file)                file_monitor_dict = {                                     ''path'': filepath,                                      ''mtime'': os.path.getmtime(filepath)                                     }                 result_list.append(file_monitor_dict)    return result_listdef monitor_and_ftp(server,                       username,                       password,                       local_dir,                       remote_dir,                       encrypt=False,                       walk=False):    ''''''Monitor local files and when an update is found connect and upload''''''    print ''Monitoring changes in (%s).'' % (os.path.abspath(local_dir))    print ''(Use ctrl-c to exit)''    last_files_list = _get_local_files(local_dir)    while True:        try:            time.sleep(SLEEP_SECONDS)            latest_files_list = _get_local_files(local_dir)            files_to_update = []            for idx in xrange(len(latest_files_list)):                if idx < len(last_files_list):                    # compare last modified times                    if latest_files_list[idx][''mtime''] > last_files_list[idx][''mtime'']:                        files_to_update.append(latest_files_list[idx])                else:                    # add the file to the list (new file)                    files_to_update.append(latest_files_list[idx])            if files_to_update:                print                print ''Detected NEW or CHANGED file(s), attempting to send ...''                print                is_success = upload_all(server,                                        username,                                        password,                                        local_dir,                                         remote_dir,                                         files_to_update,                                         encrypt,                                         walk)                if not is_success:                    break            else:                print ''.'',            last_files_list = latest_files_list[:] # copy the list to hold        except KeyboardInterrupt:            print            print ''Exiting.''            breakdef upload_all(server,                 username,                 password,                 base_local_dir,                 base_remote_dir,                 files_to_update=None,                 encrypt=False,                 walk=False):    ''''''Upload all files in a given directory to the given remote directory''''''    continue_on = False    login_ok = False    server_connect_ok = False    base_local_dir = os.path.abspath(base_local_dir)    base_remote_dir = os.path.normpath(base_remote_dir)    if files_to_update:        local_files = files_to_update    else:        local_files = _get_local_files(base_local_dir, walk)    if local_files:        if not encrypt: # Use standard FTP            ftp_h = ftplib.FTP()        else: # Use sftp            ftp_h = psftplib.SFTP()        try:            ftp_h.connect(server)            server_connect_ok = True        except socket.gaierror, e:            print ''ERROR -- Could not connect to (%s): %s'' % (server, str(e.args))        except IOError, e:            print ''ERROR -- File not found: %s'' % (str(e.args))        except socket.error, e:            print ''ERROR -- Could not connect to (%s): %s'' % (server, str(e.args))        ftp_path_tools = FtpAddOns(ftp_h)        if server_connect_ok:            try:                ftp_h.login(username,password)                print ''Logged into (%s) as (%s)'' % (server, username)                login_ok = True            except ftplib.error_perm, e:                print ''ERROR -- Check Username/Password: %s'' % (str(e.args))            except psftplib.ProcessTimeout, e:                print ''ERROR -- Check Username/Password (timeout): %s'' % (str(e.args))            if login_ok:                for file_info in local_files:                    filepath = file_info[''path'']                    path, filename = os.path.split(filepath)                    remote_sub_path = path.replace(base_local_dir, '''')                    remote_path = path.replace(base_local_dir, base_remote_dir)                    remote_path = remote_path.replace(''\\'', ''/'') # Convert to unix style                    if not ftp_path_tools.ftp_exists(remote_path):                        ftp_path_tools.ftp_mkdirs(remote_path)                    # Change to directory                    try:                        ftp_h.cwd(remote_path)                        continue_on = True                    except ftplib.error_perm, e:                        print ''ERROR -- %s'' % (str(e.args))                    except psftplib.PsFtpInvalidCommand, e:                        print ''ERROR -- %s'' % (str(e.args))                    if continue_on:                        if os.path.exists(filepath):                            f_h = open(filepath,''rb'')                            filename = os.path.split(f_h.name)[-1]                            display_filename = os.path.join(remote_sub_path, filename)                            display_filename = display_filename.replace(''\\'', ''/'')                            print ''Sending (%s) ...'' % (display_filename),                            send_cmd = ''STOR %s'' % (filename)                            try:                                ftp_h.storbinary(send_cmd, f_h)                                f_h.close()                                print ''Done!''                             except Exception, e:                                print ''ERROR!''                                print str(e.args)                                print                        else:                            print "WARNING -- File no longer exists, (%s)!" % (filepath)                ftp_h.quit()                print ''Closing Connection''    else:        print ''ERROR -- No files found in (%s)'' % (base_local_dir)    return continue_onif __name__ == ''__main__'':    import optparse    default_config_file = u''ftpallcfg.py''    # Create parser, and configure command line options to parse    parser = optparse.OptionParser()    parser.add_option("-l", "--local_dir",                      dest="local_dir",                      help="Local Directory (Defaults to CWD)",                      default=''.'')    parser.add_option("-r", "--remote_dir",                      dest="remote_dir",                      help="[REQUIRED] Target Remote directory",                      default=None)    parser.add_option("-u", "--username",                      dest="username",                      help="[REQUIRED] username",                      default=None)    parser.add_option("-s","--server",                      dest="server",                      help="[REQUIRED] Server Address",                      default=None)    parser.add_option("-e", "--encrypt",                      action="store_true",                       dest="encrypt",                      help="Use sftp",                      default=False)    parser.add_option("-m",                       action="store_true",                       dest="monitor",                      help="Keep process open and monitor changes",                      default=False)    parser.add_option("-w",                       action="store_true",                       dest="walkdir",                      help="Walk sub directories of the given directory to find files to send.",                      default=False)    (options,args) = parser.parse_args()    if (options.username and options.server and options.remote_dir) or \        os.path.exists(default_config_file):        local_dir = options.local_dir        if os.path.exists(default_config_file):            sys.path.append(''.'')            import ftpallcfg            try:                server = ftpallcfg.server                username = ftpallcfg.username                remote_dir = ftpallcfg.remote_dir                encrypt = ftpallcfg.encrypt                monitor = ftpallcfg.monitor                walk = ftpallcfg.walk            except AttributeError, e:                print "ERROR --", str(e.args)                print                print ''Value(s) missing in %s file!  The following values MUST be included:'' % (default_config_file)                print ''================================''                print ''server = <server to ftp to>''                print ''username = <Username for access to given server>''                print ''remote_dir = <remote server directory>''                print ''encrypt= True/False''                print ''monitor = True/False''                print ''walk == True/False''                print ''================================''                 sys.exit()        else:            server = options.server            username = options.username            remote_dir = options.remote_dir            encrypt = options.encrypt            monitor = options.monitor            walk = options.walkdir        # get the user password        prompt = ''Password (%s@%s): '' % (username, server)        if os.isatty(sys.stdin.fileno()):            p = getpass.getpass(prompt)        else:            #p = sys.stdin.readline().rstrip()            p = raw_input(prompt).rstrip()        if options.encrypt:            print ''>> Using sftp for secure transfers <<''            print        if monitor:            try:                monitor_and_ftp(server,username,p,local_dir, remote_dir, encrypt, walk)            except KeyboardInterrupt:                print ''Exiting...''        else:              try:                upload_all(server, username, p, local_dir, remote_dir, [], encrypt, walk)            except KeyboardInterrupt:                print ''Exiting...''    else:        print ''ERROR -- Required option not given!''        print __revision__        print __doc__        print        parser.print_help()

Ajax将文件从浏览器上传到FTP服务器

Ajax将文件从浏览器上传到FTP服务器

是否可以使用ajax将文件从浏览器升级到FTP服务器?

答案1

小编典典

不会。浏览器不提供允许从JavaScript写入FTP的API。

您可以将文件发布到HTTP端点,然后使用服务器端代码将其推送到FTP服务器。

java实现将文件上传到ftp服务器的方法

java实现将文件上传到ftp服务器的方法

这篇文章主要介绍了java实现将文件上传到ftp服务器的方法,结合实例形式分析了基于java实现的ftp文件传输类定义与使用方法,需要的朋友可以参考下

本文实例讲述了java实现将文件上传到ftp服务器的方法。分享给大家供大家参考,具体如下:

工具类:

package com.fz.common.util; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.text.SimpleDateFormat; import java.util.Date; import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPReply; public class FileUtil { /** * * @date Sep 26, 2011 10:17:39 AM * @return * @author zhangh */ public static DataInputStream getinput(){ DataInputStream d = null; try { d = new DataInputStream(new FileInputStream("c:/wmc.dat")); return d; } catch (FileNotFoundException e) { // Todo Auto-generated catch block e.printstacktrace(); } return d; } /** * * @date Sep 26, 2011 10:17:44 AM * @param whites * @return * @author zhangh */ public static boolean creatWhiteManageFile(byte[] whites,String file) { DataOutputStream d; try { d = new DataOutputStream(new FileOutputStream(file)); d.write(whites); d.flush(); } catch (Exception e) { // Todo Auto-generated catch block return false; // e.printstacktrace(); } return true; } /** * * @date Sep 16, 2011 4:39:22 PM * @param url * @param username * @param password * @param path * @param filename * @param input * @return * @author zhangh */ public static boolean uploadFile(String url, String username, String password, String path, String filename, InputStream input) { boolean success = false; FTPClient ftp = new FTPClient(); try { int reply; ftp.connect(url); // 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.changeWorkingDirectory(path); ftp.storeFile(filename, input); ftp.logout(); input.close(); success = true; } catch (IOException e) { e.printstacktrace(); } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException ioe) { } } } return success; } /** * * 方法名称:uploadFileFtp * 方法描述:黑名名单,黑用户文件上传ftp服务器 * @param url * @param username * @param password * @param path * @param filename * @param input * @param input2 * @return * boolean * version 1.0 * author wuxq * Oct 26, 2011 3:19:09 PM */ public static boolean uploadFileFtp(String url, String username, String password, String path, String filename, InputStream input, InputStream input2) { Date date = new Date(); SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String time = formatter.format(date); boolean success = false; FTPClient ftp = new FTPClient(); try { int reply; ftp.connect(url); ftp.login(username, password);// 登录 reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); return success; } ftp.changeWorkingDirectory(path); ftp.storeFile(filename, input); ftp.storeFile(filename + time, input2); ftp.logout(); input.close(); success = true; } catch (IOException e) { e.printstacktrace(); } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException ioe) { } } } return success; } }

读取配置文件:

package com.fz.fzbike.domain; import java.io.BufferedInputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Properties; import org.apache.log4j.Logger; import com.eNets.framework.util.SysConstants; /** * 获取ftp服务器信息的bean类 * * @author wuxq * */ public class SysConstats { private static Logger log = Logger.getLogger(SysConstats.class); public static String FTPSERVER;// ftp服务器ip地址 public static String FTPUSERNAME;// ftp服务器用户名 public static String FTPPASSWORD;// ftp服务器用户密码 public static String ENVELOPERESULTROOT;// 存放ftp服务器的路径 public SysConstats() { try { InputStream in = new BufferedInputStream(new FileInputStream( SysConstants.PUBLIC_PATH.substring(0, SysConstants.PUBLIC_PATH.length() - 7) + "/bidfileconfig.properties")); Properties prop = new Properties(); prop.load(in); SysConstats.FTPSERVER = prop.getProperty("ftpServer", "none"); SysConstats.FTPUSERNAME = prop.getProperty("ftpUserName", "none"); SysConstats.FTPPASSWORD = prop.getProperty("ftpPassword", "none"); SysConstats.ENVELOPERESULTROOT = prop.getProperty( "envelopeResultRoot", "none"); log.debug("读取ftp配置信息成功!"); } catch (IOException e) { log.debug("读取ftp配置信息失败!"); e.printstacktrace(); } } public static String getFTPSERVER() { return FTPSERVER; } public static void setFTPSERVER(String ftpserver) { FTPSERVER = ftpserver; } public static String getFTPUSERNAME() { return FTPUSERNAME; } public static void setFTPUSERNAME(String ftpusername) { FTPUSERNAME = ftpusername; } public static String getFTPPASSWORD() { return FTPPASSWORD; } public static void setFTPPASSWORD(String ftppassword) { FTPPASSWORD = ftppassword; } public static String getENVELOPERESULTROOT() { return ENVELOPERESULTROOT; } public static void setENVELOPERESULTROOT(String enveloperesultroot) { ENVELOPERESULTROOT = enveloperesultroot; } public static void main(String args[]) { new SysConstats(); } }

将文件上传ftp:

package com.fz.fzbike.biz; import java.io.BufferedInputStream; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.text.DecimalFormat; import com.eNets.basesys.user.vo.UserVO; import com.eNets.framework.assemble.RequestHashNew; import com.eNets.framework.database.DBConnection; import com.fz.common.util.FileUtil; import com.fz.fzbike.common.StringUtil; import com.fz.fzbike.domain.SysConstats; /** * 上传卡内码到ftp服务器 生成bat文件 * * @author wuxq 2011-09-28 */ public class UploadCardInNoFtpAction { /** * * 方法名称:uploadFtp 方法描述:上传文件到ftp * * @param reh * void version 1.0 author wuxq Sep 28, 2011 10:38:38 AM */ public void uploadFtp(RequestHashNew reh) { String cardType = reh.get("cardType").toString(); DBConnection dbc = reh.getDBC();// 链接数据库 dbc.endTran(); // 判断是否是空值 空有可能是挂失,退出挂失, 退出黑名单, 根据卡id得到卡类型 if (StringUtil.isNull(cardType)) { String cardtypesql = "select ci.card_type from lc_t_card_info ci where ci.card_id=" + reh.get("SELECTEDID"); cardType = dbc.getList0(cardtypesql); } String top = "c:/upload/"; String file = top + "bmc.dat"; // 定义一个目录存放临时的黑名单bat文件 String whiteFile = top + "wmc.dat";// 定义一个目录存放临时的白名单bat文件 String buserfile = top + "buser.dat"; // 定义一个目录存放临时的黑用户文件 String fileID = dbc.setoracleGlideValue("LC_T_UPGRADE_FILE");// 得到文件表的序列号 // 得到当前用户的ID UserVO userVo = reh.getUserVO(); String UserID = userVo.getUserID(); DecimalFormat df = new DecimalFormat("0.0"); if (cardType.equals("7")) { StringBuffer bf = new StringBuffer(1024); bf .append( "select distinct card_in_no from(select tc.card_in_no") .append( " from lc_t_blacklist tb left join lc_t_card_info tc") .append( " on tb.card_id = tc.card_id where tc.card_type = 7") .append(" and tb.whether_effective = 1 union all select") .append(" tc.card_in_no from lc_t_card_loss cl left join") .append( " lc_t_card_info tc on cl.card_id=tc.card_id where tc.card_type = 7 and") .append(" cl.whether_effective=1) t order by t.card_in_no");// 黑名单及挂失记录表中所有的管理员记录 StringBuffer bffer = new StringBuffer(1024); bffer .append("select ti.card_in_no from lc_t_card_info ti") .append( " where ti.card_type=7 and ti.card_make_status=2 order by ti.card_in_no");// 卡信息表中所有的管理员记录 // 定义一个数组来接收黑名单中排序好的管理员卡内码 String arr[][] = dbc.getArr(bf.toString()); // 定义一个数组来接收卡信息表中排序好的管理员卡内码 String listarr[][] = dbc.getArr(bffer.toString()); upload_f(arr, file); // 得到黑名单bat文件的版本号, 初始值为1.0 String vesionsql = "select file_vesion from(select row_number() over(ORDER BY t.file_vesion DESC) num," + "t.file_vesion from lc_t_upgrade_file t where t.file_type=2) where num=1"; String vesion = dbc.getList0(vesionsql); double ve = 1.0;// 定义黑名单版本编号变量,初始值为1.0 /* * 数据库中存在旧版本则在版本增加0.1 */ if (StringUtil.isNotNull(vesion)) { ve = (Double.parseDouble(vesion) + 0.1); } vesion = df.format(ve); // 版本记录sql语句 String bmcsql = "insert into lc_t_upgrade_file values(" + fileID + ",'" + file + "','" + vesion + "','2',sysdate," + UserID + ")"; dbc.insertDB(bmcsql);// 持久化到数据库 upload_f(listarr, whiteFile); // 得到白名单bat文件的版本号, 初始值为1.0 String vesionsql2 = "select file_vesion from(select row_number() over(ORDER BY t.file_vesion DESC) num," + "t.file_vesion from lc_t_upgrade_file t where t.file_type=5) where num=1"; String vesion2 = dbc.getList0(vesionsql2); double ve2 = 1.0;// 定义白名单版本编号变量,初始值为1.0 /* * 数据库中存在旧版本则在版本增加0.1 */ if (StringUtil.isNotNull(vesion2)) { ve2 = (Double.parseDouble(vesion2) + 0.1); } String bfileID = dbc.setoracleGlideValue("LC_T_UPGRADE_FILE");// 得到文件表的序列号 vesion2 = df.format(ve2); // 版本记录sql语句 String bmcsql2 = "insert into lc_t_upgrade_file values(" + bfileID + ",'" + whiteFile + "','" + vesion2 + "','5',sysdate," + UserID + ")"; dbc.insertDB(bmcsql2);// 持久化到数据库 } else { StringBuffer bf2 = new StringBuffer(1024); bf2 .append( "select distinct card_in_no from (select tc.card_in_no") .append( " from lc_t_blacklist tb left join lc_t_card_info tc") .append( " on tb.card_id = tc.card_id where tc.card_type 7") .append(" and tb.whether_effective = 1 union all select") .append(" tc.card_in_no from lc_t_card_loss cl left join") .append(" lc_t_card_info tc on cl.card_id = tc.card_id") .append(" where tc.card_type 7 and cl.whether_effective") .append(" = 1) t order by t.card_in_no");// 黑名单表及挂失用户表中所有非管理员记录 // 定义一个数组来接收黑用户中排序好的用户卡内码 String arr2[][] = dbc.getArr(bf2.toString()); upload_f(arr2, buserfile); // 得到黑用户bat文件的版本号, 初始值为1.0 String husersql = "select file_vesion from(select row_number() over(ORDER BY t.file_vesion DESC) num," + "t.file_vesion from lc_t_upgrade_file t where t.file_type=4) where num=1"; String vesion3 = dbc.getList0(husersql); double ves = 1.0;// 定义黑用户版本编号变量,初始值为1.0 /* * 数据库中存在旧版本则在版本增加0.1 */ if (StringUtil.isNotNull(vesion3)) { ves = (Double.parseDouble(vesion3) + 0.1); } vesion3 = df.format(ves); // 版本记录sql语句 String husersql = "insert into lc_t_upgrade_file values(" + fileID + ",'" + buserfile + "','" + vesion3 + "','4',sysdate," + UserID + ")"; dbc.insertDB(husersql);// 持久化到数据库 } } /** * * 方法名称:writeLong 方法描述:向输出流中写长整型 * * @param input * @return byte[] version 1.0 author wuxq Sep 28, 2011 10:54:58 AM */ public static byte[] writeLong(long input) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream os = new DataOutputStream(baos); try { os.writeLong(Long.reverseBytes(input)); } catch (IOException e) { // Todo Auto-generated catch block e.printstacktrace(); } byte[] b = baos.toByteArray(); return b; } /** * * 方法名称:upload_f 方法描述:把文件上传到ftp服务器 * * @param arr * @param file * void version 1.0 author wuxq Oct 8, 2011 11:37:27 AM */ public static void upload_f(String[][] arr, String file) { byte by[] = null; byte[] result = new byte[1]; if (StringUtil.isNotNull(arr)) { result = new byte[arr.length * 4]; int position = 0; for (int i = 0; i

更多关于java相关内容感兴趣的读者可查看本站专题:《Java文件与目录操作技巧汇总》、《Java数据结构与算法教程》、《Java操作DOM节点技巧总结》和《Java缓存操作技巧汇总》

希望本文所述对大家java程序设计有所帮助。

Java将文件上传到ftp服务器

Java将文件上传到ftp服务器

本文实例为大家分享了Java将文件上传到ftp服务器的具体代码,供大家参考,具体内容如下

首先简单介绍一下什么是FTP,以及如何在自己的电脑上搭建一个ftp服务器;

—— FTP是文件传输协议(FTP)是一种客户端/服务器协议,用于将文件传输到主机或与主机交换文件。它可以使用用户名和密码进行身份验证。匿名 FTP 允许用户从 Internet 访问文件,程序和其他数据,而无需用户 ID 或密码。总之就是方便一个可以上传下载文件的地方。

要实现上传文件,首先要在本地创建一个ftp服务器(win10系统);

一、本地创建一个其他用户

二、创建FTP目录

三、账户绑定FTP目录,登录验证

四、FTP目录创建好之后可以通过你选择的ip 进行访问 ftp://ip地址,账号密码就是你所设置的用户的账号密码

下面写javaFTP上传工具类代码,复制可用

maven依赖

<dependency>
        <groupId>commons-net</groupId>
        <artifactId>commons-net</artifactId>
        <version>3.1</version>
</dependency>
public class FtpUtil {


    /**
     * Description: 向FTP服务器上传文件
     * @param host FTP服务器hostname
     * @param port FTP服务器端口
     * @param username FTP登录账号
     * @param password FTP登录密码
     * @param basePath FTP服务器基础目录
     * @param filePath FTP服务器文件存放路径。文件的路径为basePath+filePath
     * @param filename 上传到FTP服务器上的文件名
     * @param input 输入流
     * @return 成功返回true,否则返回false
     */
    public static boolean uploadFile(String host, int port, String username, String password, String basePath,
                                     String filePath, String filename, InputStream input) {
        boolean result = false;
        FTPClient ftp = new FTPClient();
        try {
            int reply;
            ftp.connect(host, port);// 连接FTP服务器
            // 如果采用默认端口,可以使用ftp.connect(host)的方式直接连接FTP服务器
            ftp.login(username, password);// 登录
            reply = ftp.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftp.disconnect();
                return result;
            }
            //切换到上传目录
            if (!ftp.changeWorkingDirectory(basePath+filePath)) {
                //如果目录不存在创建目录
                String[] dirs = filePath.split("/");
                String tempPath = basePath;
                for (String dir : dirs) {
                    if (null == dir || "".equals(dir)) continue;
                    tempPath += "/" + dir;
                    if (!ftp.changeWorkingDirectory(tempPath)) {  //进不去目录,说明该目录不存在
                        if (!ftp.makeDirectory(tempPath)) { //创建目录
                            //如果创建文件目录失败,则返回
                            System.out.println("创建文件目录"+tempPath+"失败");
                            return result;
                        } else {
                            //目录存在,则直接进入该目录
                            ftp.changeWorkingDirectory(tempPath);
                        }
                    }
                }
            }
            //设置上传文件的类型为二进制类型
            ftp.setFileType(FTP.BINARY_FILE_TYPE);
            //上传文件
            if (!ftp.storeFile(filename, input)) {
                return result;
            }
            input.close();
            ftp.logout();
            result = true;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException ioe) {
                }
            }
        }
        return result;
    }

    /**
     * Description: 从FTP服务器下载文件
     * @param host FTP服务器hostname
     * @param port FTP服务器端口
     * @param username FTP登录账号
     * @param password FTP登录密码
     * @param remotePath FTP服务器上的相对路径
     * @param fileName 要下载的文件名
     * @param localPath 下载后保存到本地的路径
     * @return
     */
    public static boolean downloadFile(String host, int port, String username, String password, String remotePath,
                                       String fileName, String localPath) {
        boolean result = false;
        FTPClient ftp = new FTPClient();
        try {
            int reply;
            ftp.connect(host, port);
            // 如果采用默认端口,可以使用ftp.connect(host)的方式直接连接FTP服务器
            ftp.login(username, password);// 登录
            reply = ftp.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftp.disconnect();
                return result;
            }
            ftp.changeWorkingDirectory(remotePath);// 转移到FTP服务器目录
            FTPFile[] fs = ftp.listFiles();
            for (FTPFile ff : fs) {
                if (ff.getName().equals(fileName)) {
                    File localFile = new File(localPath + "/" + ff.getName());

                    OutputStream is = new FileOutputStream(localFile);
                    ftp.retrieveFile(ff.getName(), is);
                    is.close();
                }
            }
            ftp.logout();
            result = true;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException ioe) {
                }
            }
        }
        return result;
    }
    //ftp上传文件测试main函数
    public static void main(String[] args) {
        //上传
        try {
            FileInputStream in=new FileInputStream(new File("D:\\text.txt"));
            boolean flag = uploadFile("ip", 21, "username", "password", "/text","/wenjian", "hello.txt", in);
            System.out.println(flag);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        //下载
        boolean b = downloadFile("ip", 21, "username", "password", "/text/wenjian", "hello.txt", "D://");
        System.out.println(b);
    }

java代码中都有注释,就不解释了,下面有一个main 方法,可以直接进行测试。以上就是使用java向FTP文件上传的全部内容。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

您可能感兴趣的文章:
  • Java实现图片文件上传
  • java实现文件上传和下载
  • java实现文件上传下载功能
  • Java文件上传与文件下载实现方法详解
  • JavaWeb实现多文件上传及zip打包下载
  • Eolink上传文件到Java后台进行处理

Python--文件上传到FTP服务器-- ftplib 模块

Python--文件上传到FTP服务器-- ftplib 模块

上传文件到FTP服务器

环境:pycharm + ftplib + ftp服务器

说明:把本地电脑配置信息文本文档(txt文件)上传到服务器。

ftplib 模块 函数含义:

from ftplib import FTP            #加载ftp模块
ftp=FTP()                         #设置变量
ftp.set_debuglevel(2)             #打开调试级别2,显示详细信息
ftp.connect("IPaddress","port")          #连接的ftp sever和端口
ftp.login("user","password")      #连接的用户名,密码
print ftp.getwelcome()            #打印出欢迎信息
ftp.cmd("xxx/xxx")                #进入远程目录
bufsize=1024                      #设置的缓冲区大小
filehandle=open(filename,"wb").write #以写模式在本地打开文件
ftp.retrbinaly("RETR filename.txt",file_handle,bufsize) #接收服务器上文件并写入本地文件
ftp.set_debuglevel(0)             #关闭调试模式
ftp.quit()                        #退出ftp

ftp相关命令操作
ftp.cwd(pathname)                 #设置FTP当前操作的路径
ftp.dir()                         #显示目录下所有目录信息
ftp.nlst()                        #获取目录下的文件
ftp.mkd(pathname)                 #新建远程目录
ftp.pwd()                         #返回当前所在位置
ftp.rmd(dirname)                  #删除远程目录
ftp.delete(filename)              #删除远程文件
ftp.rename(oldname, newname)#将fromname修改名称为toname。
ftp.storbinaly("STOR filename.txt",file_handel,bufsize)  #上传目标文件
ftp.retrbinary("RETR filename.txt",file_handel,bufsize)  #下载FTP文件
上传下载文件:

from ftplib import FTP
#连接并登录
def ftpconnect(host,port,username, password):
    ftp = FTP()
    #ftp.set_debuglevel(2)         #打开调试级别2,显示详细信息
    ftp.connect(host, port)          #连接
    ftp.login(username, password)  #登录,如果匿名登录则用空串代替即可
    return ftp
#下载文件    
def downloadfile(ftp, remotepath, localpath):  #remotepath:上传服务器路径;localpath:本地路径;
    bufsize = 1024                #设置缓冲块大小
    fp = open(localpath,'wb')     #以写模式在本地打开文件
    ftp.retrbinary('RETR ' + remotepath, fp.write, bufsize) #接收服务器上文件并写入本地文件
    ftp.set_debuglevel(0)         #关闭调试
    fp.close()                    #关闭文件
#上传文件
def uploadfile(ftp, remotepath, localpath):
    bufsize = 1024
    fp = open(localpath, 'rb')
    ftp.storbinary('STOR '+ remotepath , fp, bufsize)    #上传文件
    ftp.set_debuglevel(0)
    fp.close()                                    

if __name__ == "__main__":
    ftp = ftpconnect("192.168.1.2",10, "lengyazhou", "lengyazhou")
    #downloadfile(ftp, "***", "***")   
    uploadfile(ftp, "/it/12", "c:/systeminfo/it.txt")  
    ftp.quit()

我们今天的关于使用Python脚本将文件夹从本地系统上传到FTPpython本地文件上传到服务器的分享已经告一段落,感谢您的关注,如果您想了解更多关于Ajax将文件从浏览器上传到FTP服务器、java实现将文件上传到ftp服务器的方法、Java将文件上传到ftp服务器、Python--文件上传到FTP服务器-- ftplib 模块的相关信息,请在本站查询。

本文标签: