用于存储请求中的文件的 Django 视图
我正在构建一个将通过桌面应用程序操作的 Django 应用程序。目前的主要功能是发送/存储文件。基本上我需要一个带有 URL 的 django 视图,我可以在该视图上使用 POST 发送文件,并且该视图将存储文件。目前我有这样的东西 :
def upload(request):
for key, file in request.FILES.items():
path = settings.MEDIA_URL + '/upload/' + file.name
dest = open(path.encode('utf-8'), 'wb+')
if file.multiple_chunks:
for c in file.chunks():
dest.write(c)
else:
dest.write(file.read())
dest.close()
destination = path + 'files_sent.txt'
file = open(destination, "a")
file.write("got files \n")
file.close
和 urlconf:
url(r'^upload/$', upload, ),
支持发送分块文件。但这行不通。代码正确吗?我是否应该采取不同的方法,例如提供带有文件字段的模型,并在此函数中创建新的模型实例而不是将文件写入磁盘?
I'm building a django application that will be operated via desktop application. Key feature for now is sending/storing files. Basically I need a django view with URL on which I can send files with POST and this view will store the files. Currently I have something like this :
def upload(request):
for key, file in request.FILES.items():
path = settings.MEDIA_URL + '/upload/' + file.name
dest = open(path.encode('utf-8'), 'wb+')
if file.multiple_chunks:
for c in file.chunks():
dest.write(c)
else:
dest.write(file.read())
dest.close()
destination = path + 'files_sent.txt'
file = open(destination, "a")
file.write("got files \n")
file.close
and urlconf:
url(r'^upload/
that supports sending chunked files. But this doesn't work. Is the code correct ? Should I take a different approach, like providing a model with file field and in this function creating a new model instance instead of writing file to disk ?
, upload, ),
that supports sending chunked files. But this doesn't work. Is the code correct ? Should I take a different approach, like providing a model with file field and in this function creating a new model instance instead of writing file to disk ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Django 提供了用于接收和存储文件的完整 API - 您可能应该阅读 文档。
Django provides a whole API for receiving and storing files - you should probably read the documentation.