M
M
Maxim2016-08-27 12:05:54
Django
Maxim, 2016-08-27 12:05:54

How to find file path and fix escaping?

def upload_file(request):
    if request.method == 'POST':
        file = request.FILES['data']
        extension = file_type(file)
        new_name = 'test_name' + '.' + extension

        destination = open('C:\\photo\\' + new_name, 'wb+')
        k = str(destination)
        file_path = k[26:-2]

        for chunk in file.chunks():
            destination.write(chunk)
            destination.close()
        return JsonResponse({
            'file_path': file_path,
        })

Good afternoon, what method can I get the path to the file if it is in a certain directory?
As in the example above, I save the file and immediately get its full path, and not in such a terrible way as mine.
Even when passing the file path string in json format, additional escaping is added, C:\\\\photo\\\\ , how can I fix this?
def file_type(file):
    return ".".join(file.name.split('.')[-1:])

Is there a method to find out the file extension?
This method does not want to save zip, py, etc. files. What is it connected with?
Thanks in advance for your help and advice)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Y
Yuri, 2016-08-27
@maximkv25

Is there a method to find out the file extension?

import os

destination = open('C:\\photo\\' + new_name, 'wb+')
# не делайте так...
# k = str(destination)
# file_path = k[26:-2]

filename = destination.name # имя файла
filepath = os.path.abspath(filename) # полный путь к файлу
file_extension = os.path.splitext(filename)[1] # вернется кортеж: [0] - имя файла, [1] - расширение

You close the file descriptor after writing the first chunk:
for chunk in file.chunks():
    destination.write(chunk)
    destination.close()

If the file is larger than the size of one chunk (presumably 4096 bytes), then it will of course not be written to the file in its entirety.
Move destination.close() out of the loop. Better yet, work with the file through the context manager:
with open('C:\\photo\\' + new_name, 'wb+') as destination:
    for chunk in file.chunks():
        destination.write(chunk)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question