How to get uploaded file in views?

Question:

I’m trying to get uploaded data in my views. Firstly, I’m getting the path and after that I have to read the file but Django gives me an error

FileNotFoundError: [Errno 2] No such file or directory:
‘/Users/edc/PycharmProjects/wl/SM/uploads/meetings notes (1).docx

but I have that file. How can I fix that?

upload = Upload(file=f)
content = ScanDocument(upload.file.path)
upload.save()


def ScanDocument(file_path):
  text = docx2txt.process(file_path)
  return text

Note if I use url instead of path then it returns:

FileNotFoundError: [Errno 2] No such file or directory:
‘/media/Meeting%20notes%20notes%20%(1).docx’

Asked By: edche

||

Answers:

If you check your file path in error it’s invalid if it’s uploaded inside media directory.

'/Users/edc/PycharmProjects/wl/SM/uploads/meetings notes (1).docx'

Just change your code like this:

import os
from django.conf import settings


upload = Upload(file=f)
file_path = os.path.join(settings.MEDIA_ROOT, upload.file.path)
content = ScanDocument(file_path)
upload.save()


def ScanDocument(file_path):
    text = docx2txt.process(file_path)
    return text
Answered By: Ankit Tiwari
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.