只需将文件保存到 Django 中的文件夹 [英] Simply save file to folder in Django
问题描述
我有一段代码可以通过 POST 从表单中获取文件.
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 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?
编辑我的 views.py 中的上传方法:
EDIT Upload method in my 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()
推荐答案
使用 default_storage
优于 FileSystemStorage
.
您可以使用 FileSystemStorage
将文件保存到 MEDIA_ROOT
,但是当您将来更改 DEFAULT_FILE_STORAGE
后端时,这可能不再起作用.
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.
如果您使用 default_storage
,将来如果您想使用 aws、azure 等作为具有多个 Django worker 的文件存储,您的代码将无需任何更改即可运行.
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 使用示例:
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)
这篇关于只需将文件保存到 Django 中的文件夹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!