演示
说明
python制作的局域网传输文件-适用于windows平台,将电脑变为共享文件神器,手机开热点或者电脑开热点,连接后实现手机电脑一键互联,快速传输分享文件,摆脱没有数据线的烦恼,项目里面含有可执行文件以及项目源码。
实现方法
- 使用flask搭建局域网平台。
- 使用tkinter用作界面。
- 判断网口,排除不必要网口ip。
- 网址生成二维码。
- 手机端扫面二维码打开页面上传文件
- 电脑端接收文件。
- 电脑端共享文件,将文件复制到目录下,手机查看并下载。
部分源码
# -*- coding:utf-8 -*-
import psutil
import qrcode
from tkinter import *
from PIL import ImageTk
from flask import *
import os,json
import tkinter as tk # 使用Tkinter前需要先导入
import threading
import tkinter.messagebox
import loggingapp = Flask(__name__)
app.config.from_object(__name__)#禁用控制台
log = logging.getLogger('werkzeug')
log.setLevel(logging.ERROR)def GetNameByEveryDir(file_dir): # Input Root Dir and get all img in per Dir.# Out Every img with its filename and its dir and its path FileNameWithPath = [] FileName = []FileDir = []for root, dirs, files in os.walk(file_dir): for file in files: FileNameWithPath.append(os.path.join(root, file)) # 保存图片路径FileName.append(file) # 保存图片名称FileDir.append(root[len(file_dir):]) # 保存图片所在文件夹return FileName,FileNameWithPath,FileDir# 首页
@app.route('/')
def index():render_template('up_video.html',file_list=ret,all_file=len(FileName),pages=page,all_page=all_page)@app.route('/next_page/<int:page>/', methods=['GET'])
def next_page(page):filepath = os.path.join(os.path.dirname(os.path.abspath('__file__')),'phone_win_file\\')if not os.path.exists(filepath):os.makedirs(filepath)FileName,FileNameWithPath,FileDir = GetNameByEveryDir(filepath)limit = 10all_page=int(len(FileName)/limit)+1pages = int(page)if pages<=0:pages=1elif pages>=all_page:pages=int(all_page) else:pages=int(page) start = (pages - 1) * limit end = pages * limit if len(FileName) > pages * limit else len(FileName) ret = [FileName[i] for i in range(start, end)]return render_template('up_video.html',file_list=ret,all_file=len(FileName),pages=pages,all_page=all_page)@app.route('/phone_win_file/<file_name>', methods=['GET'])
def phone_win_file(file_name):try:except Exception as e:return json.dumps({'code': "502"}, ensure_ascii=False)@app.route('/up_video', methods=['post'])
def up_video():try:except Exception as e:print(e)return json.dumps({'code': "502"}, ensure_ascii=False)def run_sever():app.run(host='0.0.0.0',port=5000,debug=False,use_reloader=False)def start():global l,l1,count,ip_list,len_list,chioseif chiose==0:thre = threading.Thread(target=run_sever) # 创建一个线程运行服务器thre.setDaemon(True)thre.start() # 运行线程 l1.config(text=ip_list[count])img=qrc_img(ip_list[count])IMG=ImageTk.PhotoImage(img)l.config(image=IMG) l.image=IMG #keep a reference count+=1chiose=1tkinter.messagebox.showinfo('成功','已开启服务!')else:tkinter.messagebox.showinfo('提示','服务已运行!')def getIP():"""获取ipv4地址"""dic = psutil.net_if_addrs()ipv4_list = []for adapter in dic:#网线端口:以太网,wifi端口:WLANif '以太' in adapter or 'WLAN' in adapter:snicList = dic[adapter]for snic in snicList:if snic.family.name == 'AF_INET':ipv4 = snic.addressif ipv4 != '127.0.0.1':ipv4_list.append("http://"+ipv4+":5000")if len(ipv4_list)>=1:return ipv4_list[::-1],len(ipv4_list)else:return []def qrc_img(url): qr=qrcode.QRCode(version = 2,error_correction = qrcode.constants.ERROR_CORRECT_L,box_size=11,border=2,)qr.add_data(url)qr.make(fit=True)img = qr.make_image()return imgdef show_qrc():passdef open_dir():filepath = os.path.join(os.path.dirname(os.path.abspath('__file__')),'phone_win_file\\')if not os.path.exists(filepath):os.makedirs(filepath)os.system("start explorer %s" % filepath)def about():tkinter.messagebox.showinfo('帮助','开启服务后手机扫描显示的二维码等待页面打开,\n页面打不开说明有多个网口,\n需要切换二维码进行尝试。\n进入页面查看电脑下的文件,点击文件名下载文件到手机。\n选择手机页面中的上传文件将手机文件传到手机。\n作者:Try it.(Cxk)')def connect():import webbrowserwebbrowser.open("https://cxk-life.blog.csdn.net/")if __name__ == '__main__':root=Tk()# 设置窗口大小winWidth = 600winHeight = 400# 获取屏幕分辨率screenWidth = root.winfo_screenwidth()screenHeight = root.winfo_screenheight()x = int((screenWidth - winWidth) / 2)y = int((screenHeight - winHeight) / 2)# 设置主窗口标题root.title("局域网传输文件")# 设置窗口初始位置在屏幕居中root.geometry("%sx%s+%s+%s" % (winWidth, winHeight, x, y))# 设置窗口图标root.iconbitmap("./img/cxk.ico")# 设置窗口宽高固定root.resizable(0, 0)# 添加菜单栏f = tkinter.Menu(root)root['menu']=ff.add_command(label='关于',command=about)f.add_command(label='联系作者',command=connect)#增加背景图片photo = tk.PhotoImage(file="./img/no_bg.png")theLabel = tk.Label(root,text="",justify=tk.LEFT,image=photo,compound = tk.CENTER)theLabel.place(relx=0.8, rely=0.63, anchor=CENTER)count=0chiose=0ip_list,len_list=getIP()Button(root,text='开启服务',command=start).place(relx=0.8, rely=0.08, anchor=CENTER)Button(root,text='更换网址',command=show_qrc).place(relx=0.7, rely=0.2, anchor=CENTER)Button(root,text='文件所在',command=open_dir).place(relx=0.9, rely=0.2, anchor=CENTER)l=Label(root)l.place(relx=0.3, rely=0.5, anchor=CENTER)l1=Label(root)l1.place(relx=0.3, rely=0.05, anchor=CENTER)root.mainloop()