用于存储请求中的文件的 Django 视图

发布于 2024-09-27 20:46:22 字数 788 浏览 0 评论 0原文

我正在构建一个将通过桌面应用程序操作的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

失与倦" 2024-10-04 20:46:22

Django 提供了用于接收和存储文件的完整 API - 您可能应该阅读 文档

Django provides a whole API for receiving and storing files - you should probably read the documentation.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文