Python Forum
How can I change the uuid name of a file to his original file?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How can I change the uuid name of a file to his original file?
#1
@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?
Larz60+ write Jul-17-2023, 03:01 PM:
Please post all code, output and errors (it it's entirety) between their respective tags. Refer to BBCode help topic on how to post. Use the "Preview Post" button to make sure the code is presented as you expect before hitting the "Post Reply/Thread" button.
Fixed for you this time. Please use BBCode tags on future posts.
Reply
#2
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.
Reply
#3
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";
}
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  "[Errno 2] No such file or directory" (.py file) IbrahimBennani 13 751 Jun-17-2024, 12:26 AM
Last Post: AdamHensley
  What does .flush do? How can I change this to write to the file? Pedroski55 3 427 Apr-22-2024, 01:15 PM
Last Post: snippsat
  file open "file not found error" shanoger 8 1,547 Dec-14-2023, 08:03 AM
Last Post: shanoger
  Need to replace a string with a file (HTML file) tester_V 1 914 Aug-30-2023, 03:42 AM
Last Post: Larz60+
  logging: change log file permission with RotatingFileHandler erg 0 1,231 Aug-09-2023, 01:24 PM
Last Post: erg
  Reading data from excel file –> process it >>then write to another excel output file Jennifer_Jone 0 1,251 Mar-14-2023, 07:59 PM
Last Post: Jennifer_Jone
  unittest generates multiple files for each of my test case, how do I change to 1 file zsousa 0 1,049 Feb-15-2023, 05:34 PM
Last Post: zsousa
Thumbs Up Need to compare the Excel file name with a directory text file. veeran1991 1 1,257 Dec-15-2022, 04:32 PM
Last Post: Larz60+
Photo Making Zip file of a file and Directory Nasir 2 1,130 Oct-07-2022, 02:01 PM
Last Post: Nasir
  Need Help: Convert .pcl file to .pdf file ManuRaval 6 2,722 Sep-13-2022, 01:31 PM
Last Post: ManuRaval

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020