簡體   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