I want to create an API using DRF where I want to upload two files in two different name and a text field with a string of json. The figure below shows my postman attempt to the API.
Please help me to write my API properly. I looked for several posts in stack overflow but did not get any proper solution. I dont have any models according to the input but I want to create a standalone API and want to manipulate these files and json at runtime.
Simply something like,
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")
I assume that you are writing class based views. here is your 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"})
add this line in your urls.py
url(r'uploadFiles/$', views.multipleFileUpload.as_view(), name='uploadFiles'),
Run your Post man with the same parameter and let me know.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.