django实现上传文件读取文件内容

1.models.py加入FILEFIELD文件表字段

class TestData(models.Model):
    name = models.CharField(max_length=200)
    data = models.FileField(upload_to='testdata/file', null=True, blank=True)
    img = models.ImageField(upload_to='testdata/image', null=True, blank=True)

    def __str__(self):
        return self.name

2.settings.py设置FILEFIELD的默认保存目录MEDIA_ROOT和默认链接目录MEDIA_URL

MEDIA_URL = 'data/'
MEDIA_ROOT = 'data/'

以上表示TestData的data上传后默认保存在项目根目录/data/testdata/file中,读取链接为域名/data/testdata/file/xxx.xxx

3.views.py加入文件试图:

def myfile(request, file_id):
    f = TestData.objects.get(id=file_id)
    # 建立TestData的表单对象
    FileForm = modelform_factory(TestData,fields=['name','data','img'])
    if request.method == 'POST':
        # 提交的文件保存到f对象
        form  = FileForm(request.POST,request.FILES,instance=f)
        if form.is_valid():
            form.save()
     # app为应用命名
return HttpResponseRedirect(reverse('app:myfile',args=(file_id,))) form = FileForm({'id':f.id,'name':f.name}) return render(request, 'app/file.html', {'form': form, 'file': f})

4.url.py加入此视图映射

app_name = 'app'
urlpatterns = [
    path('myfile/<int:file_id>/',views.myfile,name= 'myfile'),
]

5.创建app/file.html模板文件,{{ form }}会自动生成文件上传的html表单对象

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>上传文件</title>
</head>
<body>
<h1>{{ file.name }}</h1>
<form enctype="multipart/form-data" method="post" id="testfile_form" novalidate="true">
{% csrf_token %}
{{ form }}
<input type="submit" value="保存" class="default" name="_save">
</form>
{% if file.data %}
<p>{{ file.data.read }}</p>
{% endif %}
{% if file.img %}
<img src="{{ file.img.url }}">
{% endif %}
</body>
</html>

完成后打开http://127.0.0.1:8000/app/myfile/1/

 可以上传文件和图片了,并且读取url和内容,以及大小

6.现在需要删除文件,views.py加入删除文件的方法,url.py加入此视图映射

def del_file(request,file_id):
    f = TestData.objects.get(id=file_id)
    f.data.delete()
    return HttpResponseRedirect(reverse('app:myfile',args=(file_id,)))
app_name = 'polls'
urlpatterns = [
    path('myfile/<int:file_id>/',views.myfile,name= 'myfile'),
    path('myfile/del/<int:file_id>/',views.del_file,name= 'del_myfile'),
]

7.app/file.html模板文件加入删除按钮代码,app为应用的命名

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>{{ question.question_text }}</h1>

{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}

<form action="{% url 'app:vote' question.id %}" method="post">
{% csrf_token %}
{% for choice in question.choice_set.all %}
    <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}">
    <label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br>
{% endfor %}
<input type="submit" value="Vote">
</form>
</body>
</html>

点击删除按钮,就可以删除文件了

原文地址:https://www.cnblogs.com/zerotest/p/14392841.html