Django實現圖片上傳

實現的是將圖片上傳存放在工程目錄下。
原生實現:
html:

   <form action="{% url 'two:upload' %}" method="post" enctype="multipart/form-data">
        <div>
            <span>上傳圖片</span><input type="file" name="icon">
        </div>
        <br/>
        <button>提交</button>
    </form>

views:
添加裝飾器@csrf_exempt可以消除cstf放跨站攻擊

@csrf_exempt
def upload(request):
    if request.method == 'GET':
        return render(request, 'upload.html')
    icon = request.FILES.get('icon')
    time_str = str(time.time()*100000)
    print(icon)
    icon_path = os.path.join(BASE_DIR, 'static/upload/{}.jpg'.format(time_str))
    print(icon_path)
    with open(icon_path, 'wb') as save_file:
        for ico in icon.chunks():
            save_file.write(ico)
            save_file.flush()
    return HttpResponse('上傳成功')

Django內置的方法:
html:

   <form action="{% url 'two:image_load' %}" method="post" enctype="multipart/form-data">
  	 {% csrf_token %}
        <div>
            <span>上傳圖片</span><input type="file" name="icon">
        </div>
        <br/>
        <button>提交</button>
    </form>

models:
在models中定義

class Imageupload(models.Model):
    i_icon = models.ImageField(upload_to='icon')

settings:
ImageField是基於MEDIA_ROOT參數來存放圖片的,所以在settings中寫入

MEDIA_ROOT = os.path.join(BASE_DIR, 'static/upload')

views:

def image_load(request):
    if request.method == 'GET':
        return render(request, 'imageload.html')
    icon = request.FILES.get('icon')
    print(username, icon)
    imageload = Imageupload()
    imageload.i_icon = icon
    imageload.save()
    return HttpResponse('上傳成功')
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章