Simply save file to folder in Django

前端 未结 4 382
野趣味
野趣味 2020-12-15 17:33

I have a piece of code which gets a file from a form via POST.

file = request.FILES[\'f\']

What would be the simplest way of saving this fi

相关标签:
4条回答
  • 2020-12-15 18:06

    you can upload files to django server : :

    from django.shortcuts import render
    from django.conf import settings
    from django.core.files.storage import FileSystemStorage
    
    def upload(request):
        folder='my_folder/' 
        if request.method == 'POST' and request.FILES['myfile']:
            myfile = request.FILES['myfile']
            fs = FileSystemStorage(location=folder) #defaults to   MEDIA_ROOT  
            filename = fs.save(myfile.name, myfile)
            file_url = fs.url(filename)
            return render(request, 'upload.html', {
                'file_url': file_url
            })
        else:
             return render(request, 'upload.html')
    
    0 讨论(0)
  • 2020-12-15 18:17

    Using default_storage is better than FileSystemStorage.

    You can save file to MEDIA_ROOT with FileSystemStorage but when you change DEFAULT_FILE_STORAGE backend in the future this may not work anymore.

    If you use default_storage, in the future if you want to use aws, azure etc as file store with multiple Django worker your code will work without any change.

    default_storage usage example:

    from django.core.files.storage import default_storage
    
    #  Saving POST'ed file to storage
    file = request.FILES['myfile']
    file_name = default_storage.save(file.name, file)
    
    #  Reading file from storage
    file = default_storage.open(file_name)
    file_url = default_storage.url(file_name)
    
    0 讨论(0)
  • 2020-12-15 18:26

    Use the following code to update a FileField or ImageField. Django will upload the file to settings.MEDIA_ROOT per default.

    from os.path import basename
    from django.core.files import File
    self.model.file_field.save(basename(path), content=File(open(path, 'rb')))
    

    Afterwords you can access:

    The path like this:

    self.model.file_field.path
    

    The url like this:

    self.model.file_field.url
    
    0 讨论(0)
  • 2020-12-15 18:29

    You can use django FileField, it support specify a upload_to parameter, like this:

    data_file = models.FileField(upload_to=content_path)
    

    Where content_path can be a string or a function which returns a string.

    0 讨论(0)
提交回复
热议问题