Django for file storage and read locally

Demand Description: The picture into the local computer folder to save the image path to the database, then read through the file path to the database;

1, the file is stored:

The front end of the file:

<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>

View function:

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":"请求错误"})

Save sent over the top is the tip of pictures to specified local folder, then the folder and file name as a relative path stored in the database, fast acquisition time for easy access;

2 documents:

First, set up in the settings.py, media is stored in the Pictures folder:

IMG_PATH = "/img/"
MEDIA_ROOT = os.path.join(BASE_DIR,'img')

url.py in:

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)

To load pictures into imga folder in the html file:

<img src="/img/7.jpg" alt="图片无法显示"/>

Guess you like

Origin www.cnblogs.com/zhufanyu/p/12520564.html