实现的是将图片上传存放在工程目录下。
原生实现:
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('上传成功')