文件上传时出现“AttributeError: 'unicode' object没有'read'属性”错误

5 投票
1 回答
9650 浏览
提问于 2025-04-16 05:19

我正在使用Pylons来上传一张图片并把它存储到硬盘上:

 <form method="post">
 <input type="file" name="picture" enctype="multipart/form-data" />
 </form>

然后在我的控制器里:

 if 'picture' in request.POST:

     i = ImageHandler()

     #Returns full path of image file
     picture_file = i.makePath()

     shutil.copyfileobj(request.POST['picture'],picture_file)

但是我收到了一个错误信息:
AttributeError: 'unicode'对象没有'read'这个属性

这是怎么回事呢?谢谢你的帮助。

1 个回答

3

现在,copyfileobj函数的两个参数都是字符串,但这个函数其实是需要文件(或者说“像文件的对象”)作为参数的。你可以这样做:

 picture_file = open(i.makePath(), 'w')

(或者直接用picture_file = i,我不太清楚你的ImageHandler类是什么样的),然后

 shutil.copyfileobj(request.POST['picture'].file, picture_file)

撰写回答