需求介绍:将图片存入本地的电脑文件夹中,将图片的路径保存到数据库,然后通过数据库的路径读取文件;
1、文件的存入:
前端文件:
<form class="form-horizontal" method="post" action="/commodityAdd/" enctype="multipart/form-data"> # enctype="multipart/form-data" 必须参数
<div class="form-group">
<label for="inputImage" class="col-sm-2 control-label">标志图片</label>
<div class="col-sm-10">
<input type="file" name="commodityImage" id="inputImage">
</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-danger">提 交</button>
</div>
</form>
视图函数:
def storage_view(request):
"""
存储数据
:param request:
:return:
"""
if request.method == "POST":
img = request.FILES.get("img")
url = "/img/"
old_name = img.name
suffix = old_name.rsplit(".")[1]
img_name = int(time.time())
dir = os.path.join(os.path.join(settings.BASE_DIR, 'img'),str(img_name)+'.'+suffix)
destination = open(dir,'wb+')
for chunk in img.chunks():
destination.write(chunk)
destination.close()
models.datainfo.objects.create(
data_photo = url + str(img_name)+'.'+suffix,
add_time = timezone.now()
)
return JsonResponse({"status":True})
else:
return JsonResponse({"status":False,"error":"请求错误"})
上边是将前端发送过来的图片保存到本地指定文件夹,然后将文件夹和文件名作为相对路径存入数据库,方便访问时快速的获取;
2、文件的获取:
首先,要在settings.py中设置,media是保存图片的文件夹:
IMG_PATH = "/img/"
MEDIA_ROOT = os.path.join(BASE_DIR,'img')
url.py中:
from django.conf.urls.static import static
from . import settings
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^api/', include('web.urls')),
]
urlpatterns += static('/img/', document_root=settings.MEDIA_ROOT)
要加载的图片,放到img
文件夹中,在html文件中:
<img src="/img/7.jpg" alt="图片无法显示"/>