django 制作上传图片并预览的效果

views.py

import json, os, uuid

def upload(request):
    return render(request, 'upload.html')


def upload_file(request):
    nid = str(uuid.uuid4())  # 加一个随机码防止上传的文件重名
    ret = {'status': True, 'data': None, 'message': None}
    obj = request.FILES.get('k3')
    file_path = os.path.join('static', nid + obj.name)
    f = open(file_path, 'wb')  # 把文件上传到静态文件夹下
    for line in obj.chunks():
        f.write(line)
    f.close()
    # 把上传来的文件路径传给前端,让前端访问来显示上传的图片以达到预览的效果
    ret['data'] = file_path
    return HttpResponse(json.dumps(ret))

 

upload.html


    
    
"fm1" action="/upload_file/" method="post" target="ifra1" enctype="multipart/form-data"> "file" name="k3" οnchange="uploadFile();"> //绑定事件,让其选择完图片后就上传并预览

预览

"preview">

 

转载于:https://www.cnblogs.com/zq8421/p/10501559.html

你可能感兴趣的:(django 制作上传图片并预览的效果)