Python Forum
How can I change the uuid name of a file to his original file? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: How can I change the uuid name of a file to his original file? (/thread-40360.html)



How can I change the uuid name of a file to his original file? - MaddoxMB - Jul-17-2023

@login_required(login_url='signin')
def upload_file(request):

    if request.method == 'POST':
        form = UploadForm(request.POST, request.FILES)
        if form.is_valid():
            file = request.FILES['file']
            file_extension = os.path.splitext(file.name)[1]
            original_filename = file.name
            file_name = str(uuid.uuid4()) + file_extension
            

            file_path = os.path.join(settings.MEDIA_ROOT, 'media', file_name)
            with open(file_path, 'wb+') as destination:
                for chunk in file.chunks():
                    destination.write(chunk)

            upload_file = Upload.objects.create

            request.session['file_name'] = file_name
            request.session['original_filename'] = original_filename

            return redirect("download/")
            
    else:
        form = UploadForm()
    return render(request, 'filetransfer/upload.html', {'form': form})


def download_file(request, file_name):
    file_path = os.path.join(settings.MEDIA_ROOT,"media", file_name)
    if not os.path.exists(file_path):
        raise Http404
    
    with open(file_path, "rb") as file:
        file_contents = file.read()
    

    response = HttpResponse(file_contents, content_type='application/force-download')


    response['Content-Disposition'] = f'attachment; filename="{file_name}"'
    
    return response


def download_page(request):
    try:
        uploaded_file = Upload.objects.last()
        file_name = request.session.get('file_name')
        original_filename = request.session.get('original_filename')
        file_path=os.path.join(settings.MEDIA_ROOT,"media",file_name)
        download_url = request.build_absolute_uri(reverse('download', args=[file_name]))

    except Upload.DoesNotExist:
        download_url = None

    return render(request, 'filetransfer/download.html', {'download_url': download_url})
how can i change the uuid name to original filename, so the file will be downloaded with it's original name?


RE: How can I change the uuid name of a file to his original file? - bowlofred - Jul-17-2023

Why are you uploading it with a UUID name instead of the original name?

If the original name is safe to rename it to, it's presumably just as safe to upload it that way. But in both cases you'd want to consider what should happen in the case of a collision.


RE: How can I change the uuid name of a file to his original file? - Pedroski55 - Jul-17-2023

Is this really a job for Python? Wouldn't it be better using PHP? I didn't know Python could do this kind of thing!

I get a lot of files each week in term time. The checks I have are:

1. no file name: go back to the input form.
2. file name too long: go back to the input form.
3. You can if you want replace any non-alphanumeric characters in the file name. ($upload_file_name = preg_replace("/[^A-Za-z0-9 \.\-_]/", '', $upload_file_name);
4. file size too small: go back to the input form.
5. file size too big: go back to the input form. (set max upload size in php.ini)

If the above is all ok, save the file and load a success webpage!
Student numbers are unique, so no problem with same name files.

Quote://Save the file $q1 is Chinese name, $q2 is student number
// __DIR__ is where the php upload file is, the CWD
$dest=__DIR__.'/upload/'. $q1 . '_' . '_' . $q2 . '_' . $upload_file_name;
if (move_uploaded_file($_FILES['my_upload']['tmp_name'], $dest)) {
$_SESSION['error'] = "Your file was successfully uploaded";
}