簡體   English   中英

在 PHP 服務多部分/表單數據文件中創建 JSON API

[英]Create a JSON API in PHP Serving multipart/form-data File

我想創建一個流式 PHP API 發送 JSON 文件(而不是字符串)。

這是給定的:

  • 我們有一個現有的 PHP REST API,它服務於 Z0ECD11C1D7A287421D148A23BBB7 類型的application/json數據。 但是,JSON 數據有時 go 可能超過 6-10 MB,具體取決於查詢。
  • Another application will request from the endpoints of the PHP REST API but should receive a JSON file to automatically act as a multipart stream.

How should I construct my HTTP Headers, JSON content, etc. in PHP to serve the JSON as a file and not as a string to make it a streaming server?

到目前為止,我嘗試了這個,似乎它正在將文件下載為file.php

<?php 
header('Content-Type: multipart/form-data');
echo '{"This is": "a test"}';

哦,好吧......它的工作原理!

為了確保它可以處理超過 10 MB 的文件,我創建了一個包含 49 MB 的file.json文件,然后這樣編碼:

<?php
header('Content-Type: multipart/form-data');
echo file_get_contents('file.json'); // 49 MB file

下載的文件file.php的內容與file.json相同,這意味着它現在被認為是一個Blob。

After collecting the multipart/form-data , the server should collect the JSON string as a stream and convert it to JSON object, like this:

const jsonData: string[] = []

/ Stream and parse the data inside JSON
const stream = streamableResponse.nodeStream()

// Collect all json string
stream.on('data', (chunk) => {
  jsonData.push(chunk)
})

// Handle error of JSON stream
stream.on('error', (error) => {
  logger.error(`An error occured when getting the file contents for ${fileName}`)
  logger.error(error)
})

// Wait for the stream to finish
stream.on('end', async () => {
   const data = JSON.parse(jsonData)
   console.log(data) // Process data
}

我早該知道,我可以使用 AWS S3 Select 自動下載批量數據,如 CSV 或 JSON,自動使用從 BE 到 FE 的事件流,而不是使用從 BE 到 FE 的 Multipart/Form-data 並使用 Blob 和 ReadableStreams處理來自 FE 的傳入 stream。

https://aws.amazon.com/blogs/developer/introducing-support-for-amazon-s3-select-in-the-aws-sdk-for-javascript/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM