首页 > 解决方案 > POST请求responseType“数组缓冲区”是否可行?

问题描述

我制作了一个将返回图像的api。起初我在 get 方法请求上尝试过它并且它可以工作,但出于安全原因,我需要让它发布方法,但 post 不像我的 get 方法那样工作。您是否认为 responseType 仅在 get 方法中可用,因为它不适用于我的 post 方法?

这是我使用有效的 get 方法的代码:

前端:

export const getImageFile = async (imageName) => {
    try {
      const { data } = await axios.get(`${apiUrl}/image/${imageName}`,{
        responseType: "arraybuffer",
      });
      const image = new Buffer.from(data, "binary").toString("base64");
      return `data:image/png;base64, ${image}`;
    } catch (err) {
      alert("File not found.");
    }
  };

后端(php symfony):

/**
     * @Route("/api/graph/image/{imageName}", methods={"GET"}, name="get- image-graph")
     */
    public function getImage($imageName)
    {
        try {
            $file = $this->parameterBag->get('kernel.project_dir').'/public/graphImage/graphs/'.$imageName;
            $response = new BinaryFileResponse($file);
            return $response;
        } catch (\Exception $e) {
            return $this->json(['error' => 'File not found'], JsonResponse::HTTP_NOT_FOUND);
        }
    }

当我使用不起作用的 POST 方法时,这是我的代码:

前端:

export const getImageFile = async (imageName) => {
    try {
      const { data } = await axios.post(`${apiUrl}/image`,{
        responseType: "arraybuffer",
        "imageName": imageName,
      });
      const image = new Buffer.from(data, "binary").toString("base64");
      return `data:image/png;base64, ${image}`;
    } catch (err) {
      alert("File not found.");
    }
  };`

backend: 

```php    
    /**
     * @Route("/api/graph/image", methods={"POST"}, name="get-image- 
     graph")
     */
    public function getImage(Request $request)
    {
        try {
            $content = json_decode($request->getContent(), true);
            $imageName = $content["imageName"];
            $file = $this->parameterBag->get('kernel.project_dir') 
            .'/public/graphImage/graphs/'.$imageName;
            $response = new BinaryFileResponse($file);
            return $response;
        } catch (\Exception $e) {
            return $this->json(['error' => 'File not found'], 
            JsonResponse::HTTP_NOT_FOUND);
        }
    }`

标签: javascriptphpsymfonyaxios

解决方案


文档中,

axios.post(url, data, config)

您的发帖请求:

const { data } = await axios.post(`${apiUrl}/image`,{
        responseType: "arraybuffer",
        "imageName": imageName,
      });

看来您混合了数据和配置。所以你的帖子请求应该是

const {data} = await axios.post(
    `${apiUrl}/image`,
    {
        "imageName": imageName,
    },
    {
        responseType: "arraybuffer"
    }
);



// In server side php,you access it like
$image = $_POST["imageName"];

如果您想将其作为 json 发送,请在配置中使用标头

    {
        responseType: "arraybuffer",
        headers: {'Content-Type': 'application/json'}
    }

推荐阅读