【web开发】11、文件的上传

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档

文章目录

  • 一、文件上传
  • 二、批量上传
  • 三、案例:混合数据(form上传)
  • 四、启用media
  • 五、案例:混合数据(Modelform上传)
    • 小结



提示:以下是本篇文章正文内容,下面案例可供参考

一、文件上传

图片文件上传:在form 里添加 enctype=“multipart/form-data”
取值:request.POST和request.FILES

#upload_list.html
<div class="container">
        <form method="post" enctype="multipart/form-data">
            {% csrf_token %}
            <input type="text" name="username">
            <input type="file" name="avatar">
            <input type="submit" value="提交">

        form>
    div>
def upload_list(request):
    if request.method == "GET":
        return render(request,'upload_list.html')
    # print(request.POST)
    # print(request.FILES)
    file_object = request.FILES.get("avatar")
    print(file_object.name)   #获取文件名

    f = open('a2.png',mode='wb')
    for chunk in file_object.chunks():
        f.write(chunk)  #写入到文件中
    f.close()
    return HttpResponse("...")

【web开发】11、文件的上传_第1张图片

二、批量上传

1.安装openpyxl

pip install openpyxl

2.< input type=“file” name=“exc”>
file_object = request.FILES.get(“exc”)

#html
<div class="panel-heading">
                <span class="glyphicon glyphicon-th-list" aria-hidden="true">span>
                批量上传
div>
<div class="panel-body">
     <form method="post" enctype="multipart/form-data" action="/depart/multi/">
          {% csrf_token %}
          <div class="form-group">
              <input type="file" name="exc">
          div>
          <input type="submit" value="上传" class="btn btn-info btn-sm">
     form>
div>
# depart_multi
def depart_multi(request):
    """批量上传 (excel文件)  """
    #1.获取用户上传的文件对象
    file_object = request.FILES.get("exc")
    print(file_object)

    #2.对象传递给openpyxl,并从中读取文件内容
    from openpyxl import load_workbook
    wb = load_workbook(file_object)   #文件路径
    sheet = wb.worksheets[0]
    # cell =sheet.cell(1,1)
    # print(cell.value)
    #3.循环获取每一行数据
    for row in sheet.iter_rows(min_row=2):
        text = row[0].value
        print(text)
        models.Department.objects.create(title=text)
    return redirect("/depart/list/")
#py
def depart_multi(request):
    """批量上传 (excel文件)  """
    #1.获取用户上传的文件对象
    file_object = request.FILES.get("exc")
    print(file_object)

    #2.对象传递给openpyxl,并从中读取文件内容
    from openpyxl import load_workbook
    wb = load_workbook(file_object)   #文件路径
    sheet = wb.worksheets[0]
    # cell =sheet.cell(1,1)
    # print(cell.value)
    
    #3.循环获取每一行数据
    for row in sheet.iter_rows(min_row=2):
        text = row[0].value
        print(text)
        models.Department.objects.create(title=text)
    return redirect("/depart/list/")

【web开发】11、文件的上传_第2张图片

三、案例:混合数据(form上传)

【web开发】11、文件的上传_第3张图片
1.< form method=“post” enctype=“multipart/form-data” action=“/depart/multi/”>

#html
<form class="form-horizontal" method="post" novalidate>
	<form method="post" enctype="multipart/form-data" novalidate>
	 {% csrf_token %}
	 {% for field in form %}
	     <div class="form-group">
	         <div class="col-sm-offset-2 col-sm-10">
	             <label>{{ field.label }}label>
	             {{ field }}
	             <span style="color: red">{{ field.errors.0 }}span>
	         div>
	     div>
	 {% endfor %}
	 <div class="panel-heading col-sm-offset-2 col-sm-10" >
	     <form method="post" enctype="multipart/form-data" action="/depart/multi/">
	         <input type="submit" value="上传" class="btn btn-info btn-ms">
	     form>
 	div>
	form>
form>

2.img = forms.FileField(label=“头像”)
form = UpFOrm(data=request.POST,files=request.FILES)

from django import forms

class UpForm(BootstrapForm):
    bootstrap_exclude_fields = ['img']
    name = forms.CharField(label="姓名")
    age = forms.IntegerField(label="年龄")
    img = forms.FileField(label="头像")


import os
def upload_form(request):
    title="Form上传"
    if request.method == "GET":
        form = UpForm()
        return render(request,'upload_form.html',{"form":form,"title":title})
    form = UpForm(data=request.POST,files=request.FILES)
    if form.is_valid():
        #1.读取图片内容,写入到文件夹中并获取文件的路径
        image_object = form.cleaned_data.get("img")
        db_file_path = os.path.join("media",image_object.name)
        media_path = os.path.join("app01",db_file_path)

        f =open(media_path,mode='wb')
        for chunk in image_object.chunks():
            f.write(chunk)
        f.close()
        #2.将图片文件路径写入到数据库
        models.Boss.objects.create(
            name = form.cleaned_data['name'],
            age = form.cleaned_data['age'],
            img = media_path,

        )
        return HttpResponse("...")
    return render(request, 'upload_form.html', {"form": form, "title": title})

四、启用media

1.在urls.py中进行配置

re_path(r’^media/(?P< path>.*)$', serve, {‘document_root’: settings.MEDIA_ROOT},name=‘media’),

2.在settings.py中

import os
MEDIA_ROOT = os.path.join(BASE_DIR,“media”)
MEDIA_URL = “/media/”

五、案例:混合数据(Modelform上传)

【web开发】11、文件的上传_第4张图片

1.models.py 定义city数据表

class City(models.Model):
    name = models.CharField(verbose_name="名称",max_length=32)
    count = models.IntegerField(verbose_name="人口")
    img = models.FileField(verbose_name="Logo",max_length=128,upload_to="city/")

2.定义ModelForm

from app01.utils.bootstrap import BootstrapModelForm

class UpModelForm(BootstrapModelForm):
    bootstrap_exclude_fields = ['img']
    class Meta:
        model = models.City
        fields = "__all__"

3.视图
GET:form =UpModelForm()
POST:form = UpModelForm(data=request.POST,files=request.FILES)

def upload_model_form(request):
    title = "ModelForm上传文件"
    if request.method == "GET":
        form =UpModelForm()
        return render(request,'upload_model_form.html',{"form":form,"title":title})
    form = UpModelForm(data=request.POST, files=request.FILES)
    if form.is_valid():
    #自动保存且存在数据库中
        form.save()
        return HttpResponse("成功")
    return render(request, 'upload_model_form.html', {"form": form, "title": title})

小结

  • 手动去写

file_object = request.FILES.get(“exc”)

  • Form组件(表单验证)
request.POST
file_object = request.FILES.get("exc")
...
  • Form组件(表单验证+自动保存数据库+自动保存文件)

media文件夹
models.py定义类文件要:
img = models.FileField(verbose_name=“Logo”,max_length=128,upload_to=“city/”)

你可能感兴趣的:(前端,windows)