繁体   English   中英

如何访问存储从 postman 发送到 Django 服务器的文件数组的发布请求正文的字段?

[英]How to access a field of the body of a post request that stores an array of files sent from postman to a Django server?

很抱歉这个麻烦的问题,但我使用 postman 将四个文件发送到 Django 服务器,我的目标是访问每个文件并获取有关它们的特定信息,例如它们的路径名和文件大小。

这是 postman 上的 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.")

我尝试了以下方法来访问发布请求正文中的文件:

  1. print(files.file)但这只给了我以下 io.BytesIO object: <_io.BytesIO object at 0x10b33c590>

  2. print(files)但这只给了我请求正文的 Files 数组中最后一个文件的路径名: Screen Shot 2022-09-11 at 10.13.48 PM.png

我究竟做错了什么? 如何访问文件并获取它们的路径名?

您需要使用request.FILES.getlist('<key>')从请求 object 中获取文件列表。

参考:https://docs.djangoproject.com/en/4.1/topics/http/file-uploads/

只需编写 request.data.getlist('field_name') 即可获取文件列表。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM