How do I get the filepath of an uploaded file?
<p>I'm having difficulty passing the path of a file to a library called Textract.</p>

<pre><code>def file_to_string(filepath):
    text = textract.process(filepath)
    print text
    return text
</code></pre>

<p>Here is my upload form in views.py</p>

<pre><code>if request.method == 'POST':
    upload_form = UploadFileForm(request.POST, request.FILES)
    if upload_form.is_valid():  
        file = request.FILES['file']
        filetosave = File(file=file, filename=file.name)
        filetosave.save()
        if validate_file_extension(file):
            request.session['text'] = file_to_string(file) # something in here
else:
    upload_form=UploadFileForm()
</code></pre>

<p>models.py</p>

<pre><code>class File(models.Model):
    filename = models.CharField(max_length=200)
    file = models.FileField(upload_to='files/%Y/%m/%d')
    upload_date=models.DateTimeField(auto_now_add =True)
    status = models.CharField(max_length=200)

    def __unicode__(self):
        return self.filename
</code></pre>

<p>Now Textract expects a path to go into <code>file_to_string(filepath)</code>. If I try to pass in the file object it gives me an error: <code>"coercing to Unicode: need string or buffer, InMemoryUploadedFile found"</code>.</p>

<p>But if it is an InMemoryUploadedFile type, how do I get the path? I understand this is stored in memory and doesn't have a path.</p>

<p>How should I handle this -- should I save the file object first and then try to access it?
If I save the file and then try <code>request.session['text'] = file_to_string(file.name)</code> it gives a <code>MissingFileError</code>, though the docs say that this should give the name of the file including the relative path from MEDIA_ROOT.</p>

<p>Thanks a lot in advance.</p>

<p>Try using <code>file_to_string(file.name)</code>.</p>

<p>Docs: <a href="https://docs.djangoproject.com/en/1.10/ref/models/fields/#django.db.models.fields.files.FieldFile.name" rel="nofollow">https://docs.djangoproject.com/en/1.10/ref/models/fields/#django.db.models.fields.files.FieldFile.name</a></p>

python django django-models django-uploads