Sorry for the cumbersome question, but I am sending four files to a Django server using postman, and my goal is to access each file and get specific information about them, like their pathname and file size.
Here's the POST request on postman: post_req_postman
And here's how it looks like when the server receives the request: request_printed_to_terminal
Basically, as shown in the screenshot and as I said, I want to access the following array in the files
field of the request:
[<InMemoryUploadedFile: Screen Shot 2022-09-11 at 10.14.05 PM.png (image/png)>, <InMemoryUploadedFile: Screen Shot 2022-09-11 at 10.14.04 PM.png (image/png)>, <InMemoryUploadedFile: Screen Shot 2022-09-11 at 10.13.51 PM.png (image/png)>, <InMemoryUploadedFile: Screen Shot 2022-09-11 at 10.13.48 PM.png (image/png)>]}
Here's is the relevant Django code that handles the file uploads:
import io
import json
from operator import itemgetter
import os
from django.http import Http404,HttpResponse
from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.parsers import JSONParser
from django.views.decorators.csrf import csrf_exempt
from google.cloud import storage
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "/Users/gabrieltorion/downloads/filestoragehelpusdefend-3082732cedb4.json"
class uploadFiles(APIView):
payLoad = None
print("Will listen for new file uploads")
bucketMemoryMax = 400_000_000_000_00
@csrf_exempt
def post(self, request):
storageClient = storage.Client()
if request.data['name'] == 'uploadFiles':
print("request.data: ", request.data)
#the screen shots are in 'files'
businessId, files = itemgetter("businessId", "files")(request.data)
userBucket = storageClient.get_bucket(businessId)
currentMemoryStorage = 0
if userBucket:
blobs = storageClient.list_blobs(businessId)
if blobs:
for blob in blobs:
currentMemoryStorage =blob.size
if currentMemoryStorage < self.bucketMemoryMax:
# Get the length of the files
pass
else:
return HttpResponse("Bucket is FULL. CANNOT UPLOAD FILES.", status=404)
return HttpResponse("Post request is received.")
I tried the following to access the files in the body of the post request:
print(files.file)
but that only gives me the following io.BytesIO object:<_io.BytesIO object at 0x10b33c590>
print(files)
but that only gives me the path name of the last file in the Files array of the body of the request:Screen Shot 2022-09-11 at 10.13.48 PM.png
What am I doing wrong? How do I access the files and get their pathnames?
CodePudding user response:
You need to get the list of files from the request object using request.FILES.getlist('<key>')
.
Refer : https://docs.djangoproject.com/en/4.1/topics/http/file-uploads/
CodePudding user response:
Just write request.data.getlist('field_name') for getting the list of files.