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>

點擊刪除按鈕,就可以刪除文件了

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM