Хотите скачать файл, который был недавно загружен пользователем в django?

Это мой models.py

from django.db import models
import os
# Create your models here.
class Fileupload(models.Model):
    file=models.FileField( upload_to='media')
    date = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.file
    def filename(self):
        return os.path.basename(self.file.name)

Это мой Views.py

from msilib.schema import File
from urllib import response
from django.shortcuts import render,HttpResponse
from .models import Fileupload
from .encryptfile import encrypt

# import required module
import os
from cryptography.fernet import Fernet

# Django file encrytion process from https://pypi.org/project/django-encrypted-files/
# Import mimetypes module
import mimetypes
# def index(request):
#     return render(request, 'index.html')

def base(request):
    if request.method == 'POST':
        file2 =request.FILES["file"]
        # name = request.FILES["file"].name
        # path = "media/"+name
        document = Fileupload.objects.create(file=file2)
        document.save()
        fname = Fileupload.filename(document)
        global path1 
        path1 ="media/"+fname
        # print(fname)

        #encrypting the uploaded file which is file2
        # opening the key
        key = Fernet.generate_key()
        with open("thekey.key","wb") as thekey:
            thekey.write(key)
        
        # opening the original file to encrypt
        with open(path1, 'rb') as file:
            original = file2.read()
            
        # encrypting the file
        encrypted = Fernet(key).encrypt(original)

        # opening the file in write mode and
        # writing the encrypted data
        with open(path1, 'wb') as encrypted_file:
            encrypted_file.write(encrypted)
        
        
        return render(request,'download.html')
    else:

        return render(request, 'base.html')

def download(request):
    # Define Django project base directory
    BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    # Define text file name
    # filename = Fileupload.filename()
    # Define the full file path
    filepath = BASE_DIR + '/media/' + filename
    # Open the file for reading content
    path1 = open(filepath, 'r')
    # Set the mime type
    mime_type, _ = mimetypes.guess_type(filepath)
    # Set the return value of the HttpResponse
    response = HttpResponse(path, content_type=mime_type)
    # Set the HTTP header for sending to browser
    response['Content-Disposition'] = "attachment; filename=%s" % filename
    # Return the response value
    return render(request, response,'base.html')
    

def decrypt(request):
      
    return render(request, 'decrypt.html')
    # return HttpResponse("This is about page")

# def encrypt(request):
#     return render(request, 'encrypt.html')
#     # return HttpResponse("This is contact page")
 
# def address(request):
#     return render(request, 'address.html')
#     # return HttpResponse("This is address page")

urls.py

from django.contrib import admin
from django.urls import path
from Home import views
from django.conf.urls.static import static
from django.conf import settings
import django.conf.urls as url 

urlpatterns = [
    path('admin/', admin.site.urls),
    path('download',views.download,name='download'),
    path('decrypt',views.decrypt,name='decrypt'),
    path('',views.base,name='base'),
] + static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) 

base.html

<form method="POST" enctype="multipart/form-data">
            {% csrf_token %}
          {% comment %} <form action="/action_page.php" > {% endcomment %}
            <label for="file" class="u-btn u-button-style u-palette-2-base u-btn-1">Select a 
             file:</label>
            <input type="file" name="file"><br><br>
            <input type="submit" value="Encrypt" class="u-btn u-btn-round u-button-style u- 
             hover-palette-1-light-1 u-palette-2-light-2 u-radius-6 u-btn-2">
          </form>

download.html

  <section class="u-align-center u-clearfix u-image u-shading u-section-1" 
      src="static/img/bghack.jpg" data-image-width="7395" data-image-height="4933" id="sec- 
         f710">
        <div class="u-clearfix u-sheet u-sheet-1">
          <h1 class="u-text u-text-default u-title u-text-1">ENCRYPTION OF FILES</h1>
          <p class="u-large-text u-text u-text-default u-text-variant u-text-2">The file has 
       been encrypted. Download the file by clicking the button below.</p>
          {% if url %}
          <div class = "download">
          <a  href="{{ url }}" type="button" download class="u-btn u-button-style u-palette-2- 
        base u-btn-1">Download the file</a>
          </div>
          {% endif %}
          
        </div>
      </section>

У меня проблема с загрузкой файла, сохраненного на носитель пользователем. А также подскажите как удалить файл после того как он был скачан. Я хочу создать сайт шифрования и дешифрования, поэтому прошу помощи в Django. e-mail: neershil67@gmail.com

просто вы можете сделать следующее:

def download(request, filename=''):
    if filename != '':
        # Define Django project base directory
        BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
        # Define the full file path
        filepath = BASE_DIR + '/media/' + filename
        # Open the file for reading content
        path = open(filepath, 'rb')
        # Set the mime type
        mime_type, _ = mimetypes.guess_type(filepath)
        # Set the return value of the HttpResponse
        response = HttpResponse(path, content_type=mime_type)
        # Set the HTTP header for sending to browser
        response['Content-Disposition'] = "attachment; filename=%s" % filename
        # Return the response value
        return response
    else:
        # Load the template
        return render(request, 'file.html')

в вашем шаблоне:

<a href="{% url 'download' filename='test.txt' %}">Download PDF</a>
Вернуться на верх