python2.7版本,使用Pycharm运行python项目的gui.py文件时提示app.py的第17行代码(也就是filename = i.file.filename)出错,错误信息:AttributeError: 'dict' object has no attribute 'filename'
但是代码已经对file进行了初始化了:
i = web.input(file = {}) #接收数据 filename = i.file.filename #获取文件名 file = i.file.file.read() #获取文件
请问为啥还是出现这个错误?
html代码为:
gui.py代码为:
# -*- coding:utf-8 -*- from Tkinter import * import tkFileDialog import urllib2 import sys import win32clipboard as w import win32con import win32api import tkMessageBox # reload(sys) # sys.setdefaultencoding("utf-8") def setText(text): w.OpenClipboard() w.EmptyClipboard() w.SetClipboardData(win32con.CF_TEXT,text) w.CloseClipboard() def upload(): filename = tkFileDialog.askopenfilename(title="选择文件")#选择文件,返回文件名 files = open(filename,'rb').read() data ='''------WebKitFormBoundaryDLanRACtPqUEBKKs Content-Disposition: form-data; name="file"; filename="%s" Content-Type: application/octet-stream [file] ------WebKitFormBoundaryDLanRACtPqUEBKKs--'''%filename.split('/')[-1] data = bytes(data) data = data.replace(bytes('[file]'),files) req = urllib2.Request('http://127.0.0.1:8080/upload',data) req.add_header('Content-Type','multipart/form-data; boundary=----WebKitFormBoundaryPZsy5bHyBCEivf53') html = urllib2.urlopen(req).read() print html ent.delete(0,END) ent.insert(0,html) def download(): files = urllib2.urlopen(ent.get()).read() filename = tkFileDialog.asksaveasfilename() with open(filename,'wb') as fn: fn.write(files) def copy(): setText(ent.get()) tkMessageBox.showinfo('ok','url已复制') root = Tk()#创建窗口 root.title("文件分享系统")#修改窗口名 root.geometry("300x130+500+300")#修改窗口大小和位置 ent = Entry(root,width = 50)#输入框 ent.grid()#显示控件 btn_upload = Button(root,text=" Upload ",command=upload) btn_upload.grid() btn_download = Button(root,text="Download",command=download) btn_download.grid() btn_copy = Button(root,text=" Copy url ",command=copy) btn_copy.grid() mainloop()#显示窗口
app.py代码为:
# -*- coding:utf-8 -*- import web urls = ( #'/my','My',#浏览器访问http://127.0.0.1:8080/my时,就会调用My这个类的GET方法 '/','Index', '/upload','Upload', )#路由 render = web.template.render('templates') class Index: def GET(self): return render.index() class Upload: def POST(self): i = web.input(file = {}) #接收数据 filename = i.file.filename #获取文件名 file = i.file.file.read() #获取文件 with open('static/%s' %filename,'wb') as fn: fn.write(file) return 'http://127.0.0.1:8080/static/%s' %filename app = web.application(urls,globals()) if __name__== '__main__':#入口函数判断,本文件调用时,__name__== '__main__',其他文件调用时,__name__==文件名 app.run()
上传文件没有成功。
问题出在上传的地方,这个Boudary后面的值不是固定的,urllib2
没有处理MIME的功能,要配合其它库比如poster
使用。
推荐你使用requests
,Python里最好的http库。
import requests
data = {'file': open('a.out','rb')} # 这里a.out是你要上传的文件名
requests.post('http://127.0.0.1:8080/upload',files=data)