Kosmo零
Kosmo零

Reputation: 4151

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

I already saw similar questions here describing same problem, peoples gives there answers and someones even respond it helped, but nothing from it totally works for me.

This is my code:

<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>

and the handler:

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

I always getting error of this kind:

  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'

I understand that python thinks that files are strings, but what I can do with it???

I tried self.request.POST.get("attachment").file.read(), self.request.POST["attachment"].file.read(), self.request.get("attachment").file.read() and self.request.POST.multi["attachment"].file.read() and maybe something else, but I always getting this error.

What I can do to read content of this file?

Upvotes: 1

Views: 1830

Answers (1)

hjpotter92
hjpotter92

Reputation: 80649

The enctype attribute value you are using is wrong. The form should be sent over:

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>

Upvotes: 3

Related Questions