찾다

 >  Q&A  >  본문

python - "AttributeError: 'dict' object has no attribute 'filename'"

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代码为:

<!DOCTYPE html>
<html>
<body>
<form action="/upload" method="post" enctype="multipart/form-data">
    <input type="file" name="file">
    <input type="submit" value="post">

</form>

</body>
</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()

PHPzPHPz2782일 전1957

모든 응답(1)나는 대답할 것이다

  • 伊谢尔伦

    伊谢尔伦2017-04-18 10:29:28

    파일 업로드에 실패했습니다.

    업로드에 문제가 있습니다. urllib2에는 MIME 처리 기능이 없습니다. poster과 같은 다른 라이브러리와 함께 사용해야 합니다.

    Python 최고의 http 라이브러리인 requests을 사용하는 것이 좋습니다.

    으아악

    회신하다
    0
  • 취소회신하다