久久r热视频,国产午夜精品一区二区三区视频,亚洲精品自拍偷拍,欧美日韩精品二区

您的位置:首頁技術文章
文章詳情頁

Django實現圖片上傳功能步驟解析

瀏覽:2日期:2024-10-09 15:57:14

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='http://m.baoyu77737.com/bcjs/{% 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中一個簡單的圖片上傳到展示就做好了

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。

標簽: Django
相關文章:
主站蜘蛛池模板: 普宁市| 常州市| 湖南省| 忻城县| 赤城县| 罗城| 湖州市| 阜新市| 迭部县| 牟定县| 平邑县| 威宁| 邵东县| 大港区| 灵宝市| 石泉县| 松阳县| 邻水| 镶黄旗| 晋江市| 团风县| 临潭县| 河曲县| 安福县| 水城县| 海晏县| 海城市| 阿城市| 通许县| 修武县| 启东市| 鲜城| 南昌市| 乌鲁木齐县| 清水河县| 景泰县| 紫阳县| 商城县| 江华| 潜江市| 乌鲁木齐市|