如何在django中获取上传的文件名 [英] how to get uploaded file name in django

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

问题描述

问题背景
我是django的新手。我试图从客户端上传文件并保存。
对于这个小狗我已经创建了以下模型。

Problem Background I am new to django. I am trying to upload the file from client and save it. For this pupose i have created below model.

from django.db import models
class UploadFile(models.Model):
    uploadfile = models.FileField(upload_to='toProcess/')

我正在使用以下模型来保存文件。

I am using this model as below to save the file.

newfile = UploadFile(uploadfile = request.FILES['file'])
newfile.save()

它是保存文件。但是现在我想要处理保存的文件。在django中,如果具有相同名称的alreday的文件存在,那么它会为原始文件名添加一些唯一的后缀。我很高兴这个意见,不想写一个新的方法来创建一个唯一的文件名。

It is saving file. But now I want to process saved file. In django, if the file with the same name alreday exists then it is adding some unique postfix to the original file name. I am happy with this approch and do not want to write a new method to create a unique filename.

Probelm-
如何获取新的唯一名称计算通过django获取文件?

Probelm- How to get the new unique name calculated by django for a file?

如果我将上传相同的文件两次,说abc.pdf,那么它会将第一个上传的文件保存为abc.pdf 和第二个上传的文件为abc_somesuffix.pdf。如何知道保存文件的名称?

Mean If I will upload a same file two times say "abc.pdf" then it will save the first uploaded file as "abc.pdf" and second uploaded file as "abc_somesuffix.pdf". How to know what is the name of saved file?

推荐答案

据我所知,文件名存储在 name 属性的模型字段,在你的情况下

As far as I know, the filename is stored in the name attribute of the model field, in your case

newfile.uploadfile.name

,文件的路径存储在

and the path of the file is stored in

newfile.uploadfile.path

请参阅<一个href =https://docs.djangoproject.com/en/1.9/topics/files/#using-files-in-models =nofollow noreferrer>官方Django 文档供进一步参考,as以及许多其他SO Q& A(例如这一个

Please see the official Django docs for further reference, as well as many other SO Q&A (e.g. this one)

如果您想为文件名采用自己的格式,您可以在 upload_to 中指定可调用模型字段的参数,如这里解释

In case you want to adopt your own format for the file name you can specify a callable in the upload_to parameter of the model field, as explained here

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

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