javascript - Is it posible to POST request the responseType "array buffer"? - Stack Overflow

admin2025-04-18  2

I made an api that will return an image. at first I tried it on get method request and it works, but for security reasons I need to make it to post method but post is not working like my get method. Do you think that responseType is available only in get method since it is not working on my post method?

Here is my code using get method that works:

frontend:

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.");
    }
  };

backend (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);
        }
    }

here is my code when I use POST method that doesnt works:

frontend:

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);
        }
    }`

I made an api that will return an image. at first I tried it on get method request and it works, but for security reasons I need to make it to post method but post is not working like my get method. Do you think that responseType is available only in get method since it is not working on my post method?

Here is my code using get method that works:

frontend:

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.");
    }
  };

backend (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);
        }
    }

here is my code when I use POST method that doesnt works:

frontend:

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);
        }
    }`
Share Improve this question edited Jun 8, 2021 at 3:10 joshoe asked Jun 8, 2021 at 3:01 joshoejoshoe 811 silver badge8 bronze badges 6
  • For post method use $image = $_POST["imageName"] Because you are not sending it as json – Indra Kumar S Commented Jun 8, 2021 at 3:18
  • I send it as json based on my frontend request. I get the image based on devtool (success request) but it is not appearing on my frontend. I think my responseType is not working when I tried it on post. – joshoe Commented Jun 8, 2021 at 3:25
  • headers: { "Content-Type": "application/json" } is not present in your post request. So try $image = $_POST["imageName"] – Indra Kumar S Commented Jun 8, 2021 at 3:29
  • I tried but it cause an error. – joshoe Commented Jun 8, 2021 at 3:33
  • try my answer and let me know – Indra Kumar S Commented Jun 8, 2021 at 4:45
 |  Show 1 more ment

1 Answer 1

Reset to default 4

From the Documentation,

axios.post(url, data, config)

Your post request:

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

It seems you mixed data and config. So your post request should be

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



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

And if you would like to send it as json, use headers in config

    {
        responseType: "arraybuffer",
        headers: {'Content-Type': 'application/json'}
    }
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1744969545a277404.html

最新回复(0)