django接收图片

划重点:

request.FILES.get('file', None)
enctype="multipart/form-data"

后端

def updateAvatar(request):
    if request.method == 'POST':
        res: dict = {'success': False, 'message': ''}
        uID = request.POST.get('uID')
        user = User.objects.filter(id=int(uID))
        if len(user) == 0:
            res['message'] = '用户不存在'
            return JsonResponse(res, safe=False)
        user = user.get()
        file_obj = request.FILES.get('file', None)
        relative_path = os.path.join('static', 'user', str(uID), 'avatar')
        dir_path = os.path.join(BASE_DIR, 'media', relative_path)
        if not os.path.exists(dir_path):  # 拼接的路径是否被创建
            os.makedirs(dir_path)
        fileName = time.strftime("%Y-%m-%d-%H%M%S") + file_obj.name
        file_path = os.path.join(dir_path, fileName)
        with open(file_path, 'wb') as f:
            for chunk in file_obj.chunks():
                f.write(chunk)
        relative_path = os.path.join(relative_path, fileName)
        user.avatorUrl = 'ip地址' + relative_path
        user.save()
        res['message'] = '修改成功'
        res['success'] = True
        res['url'] = user.avatorUrl
        res['relativePath'] = relative_path
        return JsonResponse(res)

Postman测试

django接收图片_第1张图片
django接收图片_第2张图片

前端

<form accept-charset="UTF-8" action="跳转链接" method="post" enctype="multipart/form-data">
    <div>
        <input type="file" name="t_photo" accept="image/*">
    div>
form>

你可能感兴趣的:(后端,django,python,后端)