简体   繁体   English

如何为 django 中的用户从本地目录制作文件上传器(.jpg、.mp3、.pdf 等)

[英]How to make a file uploader (.jpg, .mp3, .pdf etc) from local directory for a user in django

Need an idea about how we can get that file from the user that he has selected from the local directory and send it to database.需要了解我们如何从他从本地目录中选择的用户那里获取该文件并将其发送到数据库。

i would suggest to use the django FileField, this wont store the file in the database directly (would also cause problems with large files eg videos), but rather uploads the file to the server and stores the path in the database.我建议使用 django FileField,这不会将文件直接存储在数据库中(也会导致大文件出现问题,例如视频),而是将文件上传到服务器并将路径存储在数据库中。


EDIT:编辑:

More infos about the FileField can be found here .有关FileField的更多信息可以在这里找到。 You will need to create a ModelField in your model and define the path, where the file should be stored via upload_to .您需要在 model 中创建一个 ModelField 并定义路径,文件应通过upload_to存储在其中。

For the upload process itself you have to create a view (easiest way would be a CreateView (more infos here ). This would enable a user to access the page (view) and create a model instance with the desired file.对于上传过程本身,您必须创建一个视图(最简单的方法是CreateView此处提供更多信息)。这将使用户能够访问页面(视图)并使用所需文件创建 model 实例。


EDIT2: You'll need a simple HTML-Form for this, the CreateView will provide it for you. EDIT2:您需要一个简单的 HTML 表单,CreateView 将为您提供。 In the template you can simply use:在模板中,您可以简单地使用:

<form method="post">
    {% csrf_token %}
    {{ form }}
    <input type="submit" value="Submit">
</form>

which will lead to这将导致

<form method="post">
    <input type="hidden" value="***">
    <input type="file">
    <input type="submit" value="Submit">
</form>

I would suggest to you to have a look at Django / HTML basics.我建议你看看 Django / HTML 基础知识。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM