如何在Django中提供用户上传的文件? [英] How to serve user-uploaded files in Django?

查看:138
本文介绍了如何在Django中提供用户上传的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个Django应用,用户可以在其中上传图像,但不确定如何为它们提供服务。我可以看到两种方式:

I'm writing a Django app in which the users can upload images, and I'm not sure how to serve them. I can see two ways:

1-将其上传为静态文件:将其上传到我的 static 文件夹中项目的目录,然后运行 python manage.py collectstatic ,但是我不知道每次上传文件时如何自动运行此命令,这似乎是一个因为每次服务器都会删除并重新加载我的静态应用程序中的所有内容。

1- upload them as static files: upload them in the static folder in my project's directory, and then run python manage.py collectstatic, but I don't know how to run this command automatically every time a file is uploaded, and this seems to be a lot of processing because every time the server will delete and reload everything in my static app.

2-使用 django.views.static.serve 在我的urls.py中:

2- use django.views.static.serve in my urls.py:

url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {
        'document_root': settings.MEDIA_ROOT,
    }),

文档不推荐将其用于生产。

but the doc does not recommend it for production.

建议使用哪种方式来提供用户上传的文件?

What's the recommended way to serve user-uploaded files?

推荐答案

您上传的文件放入 MEDI A_ROOT ,并且可以使用 MEDIA_ROOT 进行投放。您需要在settings.py中设置这些参数。

Your uploaded files go in MEDIA_ROOT and can be served using MEDIA_ROOT. You need to set these parameters in settings.py.

您的开发可以通过django dev服务器为它们提供服务,但是您可以将其配置为从apache或其他服务器提供服务。

Your development you can serve them though django dev server, but you can configure it to serve from apache or other server.

引用 Django管理存储的文件

这篇关于如何在Django中提供用户上传的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆