Django实现图片上传功能步骤解析

作者:小陆同学 时间:2022-06-25 19:35:43 

1.首先是html页面的form表单的三大属性,action是提交到哪,method是提交方式,enctype只要有图片上传就要加这个属性

Django框架自带csrf_token ,所以需要在前端页面也生成csrf_token字符串,来验证真实客户


 <form action="/pic_upload/" method="POST" enctype="multipart/form-data">
   {% csrf_token %}
   <input type="file" name="file">
   <input type="submit" value="提交">
  </form>

2.如下是上传图片的接口:


def pic_upload(request):
 if request.method == "GET":
   return render(request,"helloapp/pic_upload.html",locals())
 if request.method == "POST":
   error = ""
   fp = request.FILES.get("file")
   # fp 获取到的上传文件对象
   if fp:
     path = os.path.join(STATICFILES_DIRS[0],'image/' + fp.name)  # 上传文件本地保存路径, image是static文件夹下专门存放图片的文件夹
     # fp.name #文件名
     #yield = fp.chunks() # 流式获取文件内容
     # fp.read() # 直接读取文件内容
     if fp.multiple_chunks():  # 判断上传文件大于2.5MB的大文件
       # 为真
       file_yield = fp.chunks()  # 迭代写入文件
       with open(path,'wb') as f:
         for buf in file_yield:   # for情况执行无误才执行 else
           f.write(buf)
         else:
           print("大文件上传完毕")
     else:
       with open(path,'wb') as f:
         f.write(fp.read())
       print("小文件上传完毕")
     models.ImgPath.objects.create(path=('image/' + fp.name))   # image是static文件夹下专门存放图片的文件夹
   else:
     error = "文件上传为空"
     return render(request,"helloapp/pic_upload.html",locals())
   return redirect("helloapp/pic_index/") # 重定向到首页

3.做个图片展示的页面,对图片展示对应的接口传过来的参数加以判断


  {% for img in imgs %}
  <img src="{% static img.path %}">
  {% empty %}
  <h1>您没有上传任何图片</h1>
  {% endfor %}

4.图片展示的接口:


def pic_index(request):
 imgs = models.ImgPath.objects.all()
 return render(request,'helloapp/pic_index.html',locals())

至此,Django中一个简单的图片上传到展示就做好了

来源:https://www.cnblogs.com/lutt/p/10640412.html

标签:Django,图片,上传
0
投稿

猜你喜欢

  • pre标签自动换行

    2009-03-13 13:37:00
  • python中必会的四大高级数据类型(字符,元组,列表,字典)

    2023-01-10 00:54:20
  • 对python-3-print重定向输出的几种方法总结

    2023-10-21 19:38:58
  • python实现修改固定模式的字符串内容操作示例

    2023-05-13 21:44:04
  • 网页特效文字之—压纹字

    2023-06-26 19:30:06
  • REPAIR TABLE语法介绍——MySQL数据库

    2012-01-05 19:08:59
  • 用PHP编写和读取XML的几种方式

    2023-11-18 22:30:27
  • 使用Python的PIL模块来进行图片对比

    2022-04-28 19:18:36
  • python实现apahce网站日志分析示例

    2023-03-28 23:51:08
  • Django 浅谈根据配置生成SQL语句的问题

    2023-05-10 07:48:23
  • asp生成带有样式的word文件方法

    2011-04-18 10:30:00
  • 全兼容的纯CSS级联菜单要点浅析

    2009-06-10 14:42:00
  • 小议javascript设计模式

    2009-10-09 13:31:00
  • 透彻掌握ASP分页技术

    2009-03-09 18:26:00
  • 利用python和百度地图API实现数据地图标注的方法

    2023-01-30 11:59:43
  • Python中schedule模块定时任务的使用方法(2)

    2023-09-01 09:59:59
  • Python读写JSON文件的操作详解

    2021-03-22 11:46:35
  • CSS Type set: 在线字体调整工具

    2008-03-02 15:36:00
  • Python+OpenCV图像处理——实现轮廓发现

    2023-12-12 23:30:31
  • Django 缓存配置Redis使用详解

    2021-12-27 12:34:32
  • asp之家 网络编程 m.aspxhome.com