django upload and download files

Dry goods directly on it:

1, file upload:

  a. models.py

    

from django.db import models
from . import storage

class UploadFile(models.Model):
    title = models.CharField(max_length=50)
    file = models.FileField(upload_to='./filesupload',storage=storage.FieldStorage())

    def __unicode__(self):
        return self.title

    class Meta:
        ordering = ['title']

    UploadFile create a model, the parameter indicates the position upload_to file upload,

    Also you need to set MEDIA_ROOT in the settings file before this, MEDIA_URL:

 FILE_UPLOAD_HANDLERS = [
    "django.core.files.uploadhandler.MemoryFileUploadHandler",
    "django.core.files.uploadhandler.TemporaryFileUploadHandler"
  ]

MEDIA_ROOT = os.path.join(BASE_DIR,'files')
MEDIA_URL = '/files/'

    Database synchronization

  . B New forms.py file:

class UploadFileForm(forms.Form):
    title = forms.CharField(max_length=50)
    file = forms.FileField()

  . C upload files written in views.py method in which:

def upload_file(request):
    context = {}
    if request.method == 'POST':
        form = UploadFileForm(request.POST,request.FILES)
        if form.is_valid():
            title = form.cleaned_data['title']
            file = form.cleaned_data['file']

            uploadfile = UploadFile()
            uploadfile.title = title
            uploadfile.file = file
            uploadfile.save()

            return HttpResponse('success')
    else:
        form = UploadFileForm()
    context['form'] = form
    return render(request,'upload.html',context)

  . D create a template upload.html:

<h2 align="center">上传</h2>

    <form method="POST" enctype="multipart/form-data">
        {% csrf_token %}
        {{ form.as_p }}
        <input type="submit" value="Submit">
     </form>

  e. urls.py

path('',views.upload_file,name="upload" ),

  . F effects:

2. Download:

  I am here is divided into two parts, one is the file list, another part of the file downloads

    a. views.py  

def download_file(request):
    files = UploadFile.objects.all()
    context = {}
    context['files'] = files

    return render(request,'download.html',context)

def download(request,file_pk):
    file = UploadFile.objects.filter(pk=file_pk)[0]
    filename = file.file
    name = str(filename).split('/')[-1]
    filelocal = 'Files/'+str(filename)

    file = open(filelocal) 

    def file_iterator(file_name, chunk_size=512):
        with open(file_name,'rb') as f:
            while True:
                c = f.read(chunk_size)
                if c:
                    yield c
                else:
                    break
        
    response = StreamingHttpResponse(file_iterator(filelocal))
    response['Content-Type']='application/octet-stream'
    response['Content-Disposition']='attachment;filename="'+str(name)+'"'
    return response

    download_file is a list of files to download, download the file download link. Because the file is downloaded very familiar with, so write code sucks, by file_pk the file filter from the database, filelocal path to the file is stored

    . B New urls.py file:

path('downloadlist',views.download_file,name="download_list"),
path(r'download/<int:file_pk>',views.download,name="download"),

  c. download.html:

<ul>
    {% for file in files %}
        <li>{{ file.title }}<a href="{% url 'download' file.pk %}" rel="external nofollow" >点我下载</a></li>
    {% endfor %}
</ul>

 

  d created storage.py.:

    This is in order to upload files to rename, because in the process of writing I found that when I file name containing Chinese, downloaded files error (I do not know why this is ...... ), then found a way to rename the file from the other big God blog, so files can be downloaded from the normal open.

from django.core.files.storage import FileSystemStorage
import os,time,random

class FieldStorage(FileSystemStorage):
    from django.conf import settings

    def __init__(self, location=settings.MEDIA_ROOT, base_url=settings.MEDIA_URL):
        super(FieldStorage, self).__init__(location, base_url)

    def _save(self, name, content):
        ext = os.path.splitext(name)[1]
        d = os.path.dirname(name)
        fn = time.strftime('%Y%m%d%H%M%S')
        fn = fn + '_%d' % random.randint(10000, 99999)
        name = os.path.join(d, fn + ext)
        return super(FieldStorage, self)._save(name, content)

  . E Effect:

 

Guess you like

Origin www.cnblogs.com/chrran/p/11444359.html