溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Django如何實(shí)現(xiàn)圖片上傳功能

發(fā)布時(shí)間:2020-08-01 10:34:13 來源:億速云 閱讀:237 作者:小豬 欄目:開發(fā)技術(shù)

小編這次要給大家分享的是Django如何實(shí)現(xiàn)圖片上傳功能,文章內(nèi)容豐富,感興趣的小伙伴可以來了解一下,希望大家閱讀完這篇文章之后能夠有所收獲。

1.首先是html頁面的form表單的三大屬性,action是提交到哪,method是提交方式,enctype只要有圖片上傳就要加這個(gè)屬性

Django框架自帶csrf_token ,所以需要在前端頁面也生成csrf_token字符串,來驗(yàn)證真實(shí)客戶

    <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() # 流式獲取文件內(nèi)容
      # fp.read() # 直接讀取文件內(nèi)容
      if fp.multiple_chunks():  # 判斷上傳文件大于2.5MB的大文件
        # 為真
        file_yield = fp.chunks()  # 迭代寫入文件
        with open(path,'wb') as f:
          for buf in file_yield:   # for情況執(zhí)行無誤才執(zhí)行 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.做個(gè)圖片展示的頁面,對圖片展示對應(yīng)的接口傳過來的參數(shù)加以判斷

   {% for img in imgs %}
   <img src="{% static img.path %}">
   {% empty %}
   <h2>您沒有上傳任何圖片</h2>
   {% endfor %}

4.圖片展示的接口:

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

至此,Django中一個(gè)簡單的圖片上傳到展示就做好了

看完這篇關(guān)于Django如何實(shí)現(xiàn)圖片上傳功能的文章,如果覺得文章內(nèi)容寫得不錯(cuò)的話,可以把它分享出去給更多人看到。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI