Python 只需将文件保存到 Django 中的文件夹

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26274021/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 00:18:35  来源:igfitidea点击:

Simply save file to folder in Django

pythondjangodjango-modelsdjango-forms

提问by Jon

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

我有一段代码,它通过 POST 从表单中获取文件。

file = request.FILES['f']

What would be the simplest way of saving this file to my media folder in

将此文件保存到我的媒体文件夹的最简单方法是什么

settings.MEDIA_ROOT

I was looking at this answer, among others, but I had errors refering to undefined names and invalid "chunks" method.

我正在查看这个答案等,但我在引用未定义的名称和无效的“块”方法时出错。

There must be a simple way to do this?

必须有一个简单的方法来做到这一点?

EDITUpload method in my views.py:

在我的 views.py 中编辑上传方法:

def upload(request):
    folder = request.path.replace("/", "_")
    uploaded_filename = request.FILES['f'].name

    # create the folder if it doesn't exist.
    try:
        os.mkdir(os.path.join(settings.MEDIA_ROOT, folder))
    except:
        pass

    # save the uploaded file inside that folder.
    full_filename = os.path.join(settings.MEDIA_ROOT, folder, uploaded_filename)
    fout = open(full_filename, 'wb+')

    file_content = ContentFile( request.FILES['f'].read() )

    # Iterate through the chunks.
    for chunk in file_content.chunks():
        fout.write(chunk)
    fout.close()

回答by WKPlus

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

您可以使用 django FileField,它支持指定upload_to参数,如下所示:

data_file = models.FileField(upload_to=content_path)

Where content_pathcan be a string or a function which returns a string.

wherecontent_path可以是字符串或返回字符串的函数。

回答by bhawnesh dipu

you can upload files to django server : :

您可以将文件上传到 django 服务器 ::

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')

回答by Mesut Tasci

Using default_storageis better than FileSystemStorage.

使用default_storageFileSystemStorage.

You can save file to MEDIA_ROOTwith FileSystemStoragebut when you change DEFAULT_FILE_STORAGEbackend in the future this may not work anymore.

您可以将文件保存到MEDIA_ROOTwithFileSystemStorage但是当您DEFAULT_FILE_STORAGE将来更改后端时,这可能不再起作用。

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,将来如果您想使用 aws、azure 等作为具有多个 Django 工作器的文件存储,您的代码将无需任何更改即可运行。

default_storage usage example:

default_storage 用法示例:

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)

回答by Tobias Ernst

Use the following code to update a FileFieldor ImageField. Django will upload the file to settings.MEDIA_ROOTper default.

使用以下代码更新 aFileFieldImageField. Django 将settings.MEDIA_ROOT默认上传文件。

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