zoukankan      html  css  js  c++  java
  • Django中怎么做图片上传--图片展示

    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中一个简单的图片上传到展示就做好了,接下来还想怎么耍,望多提宝贵意见或建议,我们一起来研究更炫更理想的效果
  • 相关阅读:
    strcpy和memcpy的区别《转载》
    C++数组引用
    关于C++中继承、重载、掩盖 《转载》
    对于js原型和原型链继承的简单理解(第三种,复制继承)
    对于js原型和原型链继承的简单理解(第二种,对象冒充)
    腾讯的一道js面试题(原型)
    面试题,自己写写dome总是好的
    对于js原型和原型链继承的简单理解(第一种,原型链继承)
    html+css布局小练习w3cfuns
    C#泛型列表List<T>基本用法总结
  • 原文地址:https://www.cnblogs.com/lutt/p/10640412.html
Copyright © 2011-2022 走看看