python实现ftp上传文件

python 通过ftp实现文件上传:
上传接口:
def ftp_uploadfile(request):
result = {
‘result’: ‘success’
}
ftp = ftpconnect(“服务器ip”, “用户”, “密码”)
data = request.GET
if not data:
data = request.POST
filepath = data.get(‘out_path’)
remotepath = os.path.basename(filepath)
print(remotepath)
print(‘remotepath’)

uploadfile(ftp, remotepath, filepath)
ftp.quit()

return JsonResponse({‘result’: ‘success’, ‘code’: ‘10000’})

#连接ftp
def ftpconnect(host, username, password):
ftp = FTP()
ftp.connect(host, 8020) # 连接
ftp.login(username, password) # 登录
return ftp

#上传位置
def uploadfile(ftp, remotepath, localpath):
# 获取现在时间
nowTime = datetime.datetime.now().strftime(’%Y%m%d’)
print(‘当前时间:’ + str(nowTime))
bufsize = 1024
ftp.cwd(’/data/video/’)
try:
ftp.cwd(’/data/video/’ + nowTime)
except ftplib.error_perm:
try:
ftp.mkd(’/data/video/’ + nowTime)
ftp.cwd(’/data/video/’ + nowTime)
print(‘3333333’)
except:
meg = ‘You have no authority to make directory’
print(meg)
ftp.set_pasv(1) //1,0被动与主动
fp = open(localpath, ‘rb’)
ftp.storbinary('STOR ’ + remotepath, fp, bufsize) # 上传文件
#ftp.storbinary(‘STOR urls.py’, fp, bufsize)
ftp.set_debuglevel(0)
fp.close()

发布了15 篇原创文章 · 获赞 3 · 访问量 388

猜你喜欢

转载自blog.csdn.net/weixin_44520602/article/details/104607263