我有一段代码通过POST从表单获取文件。只需将文件保存到Django中的文件夹
file = request.FILES['f']
什么是保存这个文件到我的媒体文件夹的
settings.MEDIA_ROOT
我看着this answer,其中包括最简单的方式,但我有错误指的未定义的名称和无效的“豆腐块“ 方法。
必须有一个简单的方法来做到这一点?
编辑我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()
导入ContentFile是保存在数据库中的选项?您推荐的发布解决方案似乎是正确的。你能发布错误信息吗?你读了第二篇文章的答案 - 它告诉有关chunck错误和如何解决它 – 2014-10-09 08:54:56
请看我的编辑,我现在得到“全球名称'ContentFile'没有定义” – Jon 2014-10-09 09:10:21
你可以在[django中找到它。 core.files](https://docs.djangoproject.com/en/1.7/ref/files/file/#the-contentfile-class)库 – 2014-10-09 09:13:13