1.tkinter上传图片主要用到filedialog
通过filedialog.askopenfilename()读出文件路径了就可以进行后续文件操作,比如识图等等功能
import tkinter as tk
from tkinter import filedialog
from PIL import Image
root = tk.Tk()
root.withdraw() #隐藏窗口
file_path = filedialog.askopenfilename() #文件路径
a=file_path
#二进制形式读取文件
with open(a,"rb")as f:
print(f.read())
# PIL图片展示
image=Image.open(a)
image.show()
print(a)
print(type(a))
2.django实现页面上传文件和下载
主要结合前端form表单,然后后台进行判断和保存,最后再实现下载
知识点有:csrf防止跨域攻击,content-type文件流下载,re_path正则匹配形式,request的方法等
#这是html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="{% url 'file:upload' %}" method="post" enctype="multipart/form-data"> {# 注意格式{% url 'file:upload' %} ,enctype="multipart/form-data"表示数据流形式 #}
{% csrf_token %} {# 防止跨域攻击 #}
<input type="file" name="file">
<input type="submit" value="上传">
</form>
</body>
</html>
#urls
from django.urls import path,re_path
from . import views
app_name="file" #include添加namespace报错需要添加这句app_name
urlpatterns = [
path('',views.home,name='home'),
path('test/',views.test,name='test'),
path('index/',views.index,name='index'),
path('upload/',views.upload,name='upload'),
re_path('(.+)',views.download,name='download'),
]
#views
from django.shortcuts import render
from django.http import JsonResponse,HttpResponse
# Create your views here.
def home(request):
return render(request,'file/home.html',{"aa":"bb"})
def test(request):
return render(request,'file/test.html',{"aa":"bb"})
def index(request):
return render(request,'file/index.html')
def upload(request):
#请求方式判断
if request.method == "POST":
myfile=request.FILES.get("file")
filename=myfile.name
file=myfile.read()
filesize=myfile.size
if myfile==0 or filesize==0:
return JsonResponse({'result':1000,'success':False,'msg':'必须上传文件并且不能为空'})
with open(r"file\upload\%s.txt"%filename,'wb')as f:
f.write(file)
return JsonResponse({'result':200,'success':True,'msg':'','path':'upload/%s'%filename})
return JsonResponse({'result':403,'success':False,'msg':u'访问请求错误'})
def download(request,filename):
file=open(r"file\upload\%s"%filename,'rb').read() #.decode('gb18030','ignore') "rb",encoding='gb18030',errors='ignore'
print(file)
response =HttpResponse(file)
response["content-type"]="application/octet-stream" #文件二进制流形式
response["content-disposition"]="attachment;filename=%s"%filename
return response
主要路径问题。django默认路径是project下,另外views有upload和download分别对应处理上传和下载的方法
下载文件新建了url路由,用的正则re_path,然后view里download方法