美文网首页
django实现文件上传到服务器

django实现文件上传到服务器

作者: 叶叶阿姨 | 来源:发表于2020-03-11 17:25 被阅读0次
def file_upload(request):
    # 文件上传
    if request.method == "POST":
        document_code = request.POST.get('document_code')
        file = request.FILES.get('file')  # 文件对象
        document_name = file.name  # 文件名
        document_size = file.size  # 文件大小
        document_type = document_name.split(".")[1]  # 文件类型
        document_path = 'journal/' + document_name  # 路径
        helps_id = request.POST.get('helps_id')  # 应助文章
        responders = get_id(request.POST.get('responders'))  # 应助人
        # 应助开始时间
        response_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
        # 应助结束时间
        end_response_time = (datetime.datetime.now() + datetime.timedelta(days=1)).strftime('%Y-%m-%d %H:%M:%S')
        if document_code == '全文文件':
            # 改变应助文章状态等
            data = [{"document_code": document_code,
                       "document_type": document_type,
                       "document_name": document_name,
                       "document_size": document_size / 1e3,
                       "document_path": 'seek_help/' + document_path}]
            Helps.objects.filter(Q(state=0) & Q(id=helps_id)).update(responders=responders,
                                                                     state=6,
                                                                     field_info=data,
                                                                     response_time=response_time,
                                                                     end_response_time=end_response_time)
            response = requests.post(PATH, data={'document_name': document_path, 'file': base64.b64encode(file.read())})
            print(response.text)
            return JsonResponse({'code': 200, 'data': data})

response = requests.post(PATH, data={'document_name': document_path, 'file': base64.b64encode(file.read())}) 这个方法其实就是将文件信息和转成base64的文件发到服务器那边,那边就是以下的方法存入服务器

文件存入本地的方法

 # 文件存入本地
        try:
            if os.path.exists(document_path):
                os.remove(document_path)
            with open(document_path, 'wb+') as f:
                for chunk in file.chunks():
                    f.write(chunk)
                f.close()
            return JsonResponse({'code': 200, 'data': data})

相关文章

网友评论

      本文标题:django实现文件上传到服务器

      本文链接:https://www.haomeiwen.com/subject/lakhjhtx.html