Open file to read from web form
<p>I am working on a project where I have to upload a file from file storage (via web form) to MongoDB. In order to achieve this, I need to open the file in "rb" mode, then encode the file and finally upload to MongoDb. I am stuck when opening the file "rb" mode.</p>

<pre><code>    if form.validate():
        for inFile in request.files.getlist("file"):

            connection = pymongo.MongoClient()
            db = connection.test
            uploads = db.uploads

            with open(inFile, "rb") as fin:
                f = fin.read()
                encoded = Binary(f,0)

                try:
                    uploads.insert({"binFile": encoded})
                    check = True
                except Exception as e:
                    self.errorList.append("Document upload is unsuccessful"+e)
                    check = False
</code></pre>

<p>The above code is throwing <code>TypeError: coercing to Unicode: need string or buffer, FileStorage found</code> in the <code>open</code> step, i.e. this line:</p>

<pre><code>with open(inFile, "rb") as fin:
</code></pre>

<p>Is there a way I can change my code to make it work? </p>

<p>Thanks in advance</p>

<p>The <code>FileStorage</code> object is already file-like so you can use as a file. You don't need to use <code>open</code> on it, just call <code>inFile.read()</code>.</p>

<p>If this doesn't work for you for some reason, you can save the file to disk first using <code>inFile.save()</code> and open it from there.</p>

<hr>

<p>Reference: <a href="http://werkzeug.pocoo.org/docs/0.11/datastructures/#werkzeug.datastructures.FileStorage" rel="nofollow">http://werkzeug.pocoo.org/docs/0.11/datastructures/#werkzeug.datastructures.FileStorage</a></p>

python flask