Upload PDF File API In NextJS 13 APP Folder Not Working

208 views Asked by At

I have a small App that converts PDF files to Word docs. I'm calling an external API, and everything works fine in the client component.

Here is my working code in the client component:

"use client";

import { useState, useRef } from "react";
import { useRouter } from "next/navigation";

export default function () {
  const router = useRouter();
  const [selectedFile, setSelectedFile] = useState(null);
  const [downloadLink, setDownloadLink] = useState(null);
  const [loading, setLoading] = useState(false);

  const handleFileChange = (event) => {
    setSelectedFile(event.target.files[0]);
  };

  const handleUpload = async () => {
    setLoading(true);
     var myHeaders = new Headers();
     myHeaders.append("Apikey", "my API key");

    var formdata = new FormData();
    formdata.append("inputFile", selectedFile);

    var requestOptions = {
      method: "POST",
       headers: myHeaders,
      body: formdata,
      redirect: "follow",
    };

    fetch("https...", requestOptions)
      .then((response) => response.blob())
      .then((blob) => {
        const blobUrl = URL.createObjectURL(blob);
        setDownloadLink(blobUrl);
        setLoading(false);
      })
      .catch((error) => {
        console.error("Error:", error);
        setLoading(false);
      });
  };

  return (
    <div>
      <h1>PDF to DOC Converter</h1>

      <div>
        <input type="file" name="inputFile" onChange={handleFileChange} />
        <button onClick={handleUpload}>Upload File</button>
      </div>

      {loading ? (
        <p>Loading...</p>
      ) : downloadLink ? (
        <div>
          <a href={downloadLink} download="converted.docx">
            <button>Download Original File</button>
          </a>
        </div>
      ) : null}
    </div>
  );
}

But, when I tried to convert the handleUpload function in the client side into an API in the App/api/process/rout.js as shown below:

import { NextResponse, NextRequest } from "next/server";

export async function POST(req, res) {
  const formData = await req.formData();

  const file = formData.get("inputFile");

  console.log(file, "file");

  if (!file) {
    return NextResponse.json({ success: false });
  }

  var myHeaders = new Headers();
  myHeaders.append("Apikey", "my_api_key");

  var formdata = new FormData();
  formdata.append("inputFile", file, file.name);
  console.log(file, "fileee");

  var requestOptions = {
    method: "POST",
    headers: myHeaders,
    body: formdata,
    redirect: "follow",
  };

  const response = await fetch(
    "https....",
    requestOptions
  );

  console.log(response, "responseeeee");

  if (response.statusText === "OK") {
    const responseText = await response.text();
    return NextResponse.json({ success: true, responseData: responseText });
  } else {
    return NextResponse.json({
      success: false,
      error: "An error occurred during conversion.",
    });
  }
}



The API keeps returning an error.

1

There are 1 answers

1
Sajid Aalam On

As far as I know, we need some middlewares to send files from the front end to backend. Like i used to use multer to send files to express server from next ja client side. I'm sure if vercel api supports file read or not.