How to solve "AttributeError: 'unicode' object has no attribute 'file'" once and for all in python webapp2 at file upload?

How to solve "AttributeError: 'unicode' object has no attribute 'file'" once and for all in python webapp2 at file upload?

我已经在这里看到描述相同问题的类似问题,人们给出了答案,甚至有人回复它有帮助,但没有任何内容对我完全有用。

这是我的代码:

<html>
  <body>
    <form action = "/anomalydetector" enctype = "multipart-form-data" method = "post">
      File: <input name = "attachment" type = "file" /><br />
      Analyzer sensitivity in percents: <input type = "text" name = "sensitivity" value = "10" /><br />
      <input type = "submit" value = "Analyze" />
    </form>
  </body>
</html>

和处理程序:

class AnomalyDetectorPage(webapp2.RequestHandler):
    def post(self):
        uploaded_file = self.request.POST.get("attachment");
        file_data = uploaded_file.file.read();

我总是遇到这种错误:

  File "/base/data/home/apps/s~test-ml/1.398533980585659886/main.py", line 207, in post
    file_data = uploaded_file.file.read();
AttributeError: 'unicode' object has no attribute 'file'

我明白 python 认为文件是字符串,但我能用它做什么???

我尝试了 self.request.POST.get("attachment").file.read()self.request.POST["attachment"].file.read()self.request.get("attachment").file.read()self.request.POST.multi["attachment"].file.read() 以及其他方法,但我总是遇到此错误。

如何读取此文件的内容?

您使用的 enctype 属性值有误。表格应发送至:

multipart/form-data

<html>
<body>
  <form action="/anomalydetector" enctype="multipart/form-data" method="post">
    File: <input name="attachment" type="file" />
    <br />
    Analyzer sensitivity in percents: <input type="text" name="sensitivity" value="10" />
    <br />
    <input type="submit" value="Analyze" />
  </form>
</body>
</html>