zoukankan      html  css  js  c++  java
  • Django中上传图片---避免因图片重名导致被覆盖

    上一篇文章中(https://www.cnblogs.com/lutt/p/10640412.html),我们以图片文件夹+图片名字的方式来储存图片,这样的做法会导致有重名的图片会导致之前的图片被覆盖,解决这一问题的方法:MD5时间戳,图片名称可能会重复,但是上传图片的时间生成的MD5字符串是唯一的,可以以此来作为图片保存的方式,就避免了图片重名导致覆盖的惨剧,下面来码一段详细的代码:

    from django.utils import timezone   # 获取当前时间
    import hashlib   # 给当前时间编码
    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:
                time_now = timezone.now()  # 获取当前日期时间
                print(time_now)  # 2019-04-03 00:51:21.225391+00:00 当前打印的时间格式是这样,不能直接使用,需要用MD5编码
                m = hashlib.md5()
                m.update(str(time_now).encode())   # 给当前时间编码
                time_now = m.hexdigest()
                print(time_now)  # ec3b25c7e44ded02d092c57dded2d5eb  此时为编码后的时间
                path = os.path.join(STATICFILES_DIRS[0],'image/' + time_now + fp.name)   # 上传文件本地保存路径
                # 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/' + time_now + fp.name))
            else:
                error = "文件上传为空" 
                return render(request,"helloapp/pic_upload.html",locals()) 
            return redirect(reverse("picindex") )# 重定向到首页
  • 相关阅读:
    apk应用签名获取
    git强制推送命令
    Maven 将本地jar包添加到本地仓库
    关于Plugin execution not covered by lifecycle configuration: org.apache.maven.plugins:maven-compiler-plugin的解决方案
    启动React-Native项目步骤
    Git初始化本地项目并提交远程仓库基础操作
    You have not accepted the license agreements of the following SDK components: [Android SDK Build-Tools 26.0.1, Android SDK Platform 26]
    kenkins安装
    Linux关闭防火墙和SELinux
    Linux下nginx安装配置
  • 原文地址:https://www.cnblogs.com/lutt/p/10646746.html
Copyright © 2011-2022 走看看