本帖最后由 Aitlo 于 2021-11-25 22:11 编辑
通过Python,使用Flask框架实现上传,下载,遍历文件.编写一个简单的FTP功能.
懒人精灵FTP.py 文件源码:
- from flask import Flask, request, make_response,send_from_directory
- import json
- import os
- app = Flask(__name__)
- @app.route("/server/dir",methods=["GET"])
- def get_server_dir():
- # 获取服务端文件夹文件路径
- server_file_dict = {}
- server_path = os.path.dirname(__file__)
- if os.path.isdir(server_path):
- for root,dirs,files in os.walk(server_path):
- for index,file in enumerate(files,1):
- # print(index,file)
- server_file_dict[index] = file
- return json.dumps(server_file_dict,ensure_ascii=False)
- @app.route("/download/<filename>", methods=['GET'])
- def download_file(filename):
- # 需要知道2个参数, 第1个参数是本地目录的path, 第2个参数是文件名(带扩展名)
- directory = os.getcwd() # 假设在当前目录
- response = make_response(send_from_directory(directory, filename, as_attachment=True))
- response.headers["Content-Disposition"] = "attachment; filename={}".format(filename.encode().decode('latin-1'))
- return response
- @app.route('/create/upload', methods=["GET", "POST"])
- def create_upload():
- # 接收上传文件并保存
- new_dict = {}
- print(request.files)
- file = request.files.get("file")
- file.save(file.filename)
- new_dict["userip"] = request.remote_addr
- new_dict["filestate"] = True
- new_dict[file.filename]="上传成功!"
- return str(new_dict)
- if __name__ == '__main__':
- # app.run()
- app.run(host="0.0.0.0", port="5000", debug=True)
复制代码 懒人精灵lua文件的源码:
- function UploadFile(url,filepath)
- -- 上传文件至服务端
- -- UploadFile(服务器的链接地址,上传文件的路径)
- local ret = uploadFile(url,filepath)
- print(ret)
-
- end
- -- 云端上传服务器的链接地址
- local url = "http://192.168.1.7:5000/create/upload"
- -- 本地需上传文件的路径
- local filepath = "/mnt/sdcard/test.txt"
- --UploadFile(url,filepath)
- function DownloadFile(url,filename,savefile)
- -- 访问服务端 下载文件保存本地
- -- DownloadFile(服务器的链接地址,下载的文件名,保存的文件名)
- -- 本地创建一个懒人精灵下载的文件夹
- local path = "/mnt/sdcard/懒人精灵下载"
- if fileExist(path) == false then
-
- print(mkdir(path))
-
- end
-
- local ret = downloadFile(string.format("%s/%s",url,filename),string.format("%s/%s",path,savefile))
- if ret == 0 then
- print("下载成功,文件已保存至:",string.format("%s/%s",path,savefile))
- else
- print("下载失败!")
- end
- end
- local url = "http://192.168.1.7:5000/download"
- local filename = "client.py"
- local savefile = "client.py"
- DownloadFile(url,filename,savefile)
- function GetServerFlieName(url)
- -- 遍历服务端存储文件名
- -- GetServerFlieName(服务器的链接地址)
- local ret,code = httpGet(url)
- if ret ~= nil then
- fileTab = jsonLib.decode(ret)
- print("服务器存储的文件:")
- for k,v in pairs(fileTab) do
- print(k,v)
- end
- end
-
-
- end
- local url = "http://192.168.1.7:5000/server/dir"
- GetServerFlieName(url)
复制代码 运行结果图片:
|