很抱歉有这么麻烦的问题,但我使用poster将四个文件发送到Django服务器,我的目标是访问每个文件并获取有关它们的特定信息,如路径名和文件大小。
以下是poster上的POST请求:POST_req_postman
以下是服务器收到请求时的情况:request_printed_to_terminal
基本上,如屏幕截图所示,正如我所说,我想访问请求的files
字段中的以下数组:
[<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)>]}
以下是处理文件上传的相关Django代码:
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.")
我尝试了以下方法来访问帖子请求正文中的文件:
print(files.file)
,但这只给了我以下io.BytesIO对象:<_io.BytesIO object at 0x10b33c590>
print(files)
,但这只给了我请求主体的Files数组中最后一个文件的路径名:Screen Shot 2022-09-11 at 10.13.48 PM.png
我做错了什么?如何访问文件并获取它们的路径名?
您需要使用request.FILES.getlist('<key>')
从请求对象获取文件列表。
参考:https://docs.djangoproject.com/en/4.1/topics/http/file-uploads/
您只需要编写request.data.getlist('field_name')
即可获得文件列表。