Jul-17-2023, 11:42 AM
@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?