簡體   English   中英

Django Rest框架中的多個文件上傳

[英]multiple file upload in django rest framework

我想使用DRF創建一個API,在其中我要上傳兩個文件,兩個名稱不同,文本字段為json字符串。 下圖顯示了我的郵遞員嘗試使用該API的嘗試。

在此處輸入圖片說明

請幫助我正確編寫我的API。 我在堆棧溢出中查找了幾篇文章,但沒有任何適當的解決方案。 根據輸入,我沒有任何模型,但我想創建一個獨立的API,並希望在運行時處理這些文件和json。

就像這樣

import json
from rest_framework.decorators import api_view
from rest_framework.response import Response


@api_view(['POST'])
def foo(request):
    attributes = json.loads(request.data['attributes'])  # will be a 'dict'
    xsd_file = request.data['xsd_file']  # "InMemoryUploadFile" instance
    Iccs_file = request.data['Iccs_file']  # "InMemoryUploadFile" instance
    return Response("some response")

我假設您正在編寫基於類的視圖。 這是你的view.py

class multipleFileUpload(APIView):

    def post(self, request):
    """

    :param request: 
    :return: 
    """
    try:
        #this will read attributes other than file
        str_value = request.POST["attributes"]
        print(str_value)

        #check if any file send in request if yes read all files one by one
        if len(request.FILES) != 0:
           for key in request.FILES:
               file_obj = request.FILES[key]
               print(file_obj.read()) #getting contents of the file in bytes
        return JsonResponse({"res": "got files"})
    except Exception as e:
        print(str(e))
        return JsonResponse({"res": "error"})

將此行添加到您的urls.py中

url(r'uploadFiles / $',views.multipleFileUpload.as_view(),name ='uploadFiles'),

使用相同的參數運行您的Post man,讓我知道。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM