<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Owais Shah</title>
    <description>The latest articles on DEV Community by Owais Shah (@xhowais).</description>
    <link>https://dev.to/xhowais</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1213847%2F8c8e8b3a-b480-410a-bd5f-e8cd6c7162db.jpg</url>
      <title>DEV Community: Owais Shah</title>
      <link>https://dev.to/xhowais</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/xhowais"/>
    <language>en</language>
    <item>
      <title>Next.js File Upload API Documentation</title>
      <dc:creator>Owais Shah</dc:creator>
      <pubDate>Mon, 20 Nov 2023 04:32:04 +0000</pubDate>
      <link>https://dev.to/xhowais/nextjs-file-upload-api-documentation-3863</link>
      <guid>https://dev.to/xhowais/nextjs-file-upload-api-documentation-3863</guid>
      <description>&lt;p&gt;This documentation provides a guide on setting up and using a file upload API in a Next.js application. The provided API endpoint allows you to handle file uploads efficiently.&lt;/p&gt;

&lt;h2&gt;
  
  
  API Endpoint
&lt;/h2&gt;

&lt;p&gt;The file upload API is defined in the POST handler, which is responsible for processing incoming file data and saving it to the server.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F3ty1ad6pws3xe6giuct2.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F3ty1ad6pws3xe6giuct2.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

// Import necessary modules
import { NextResponse } from "next/server";**
import path from "path";
import { writeFile } from "fs/promises";

// Define the POST handler for the file upload
export const POST = async (req, res) =&amp;gt; {
  // Parse the incoming form data
  const formData = await req.formData();

  // Get the file from the form data
  const file = formData.get("file");

  // Check if a file is received
  if (!file) {
    // If no file is received, return a JSON response with an error and a 400 status code
    return NextResponse.json({ error: "No files received." }, { status: 400 });
  }

  // Convert the file data to a Buffer
  const buffer = Buffer.from(await file.arrayBuffer());

  // Replace spaces in the file name with underscores
  const filename = file.name.replaceAll(" ", "_");
  console.log(filename);

  try {
    // Write the file to the specified directory (public/assets) with the modified filename
    await writeFile(
      path.join(process.cwd(), "public/assets/" + filename),
      buffer
    );

    // Return a JSON response with a success message and a 201 status code
    return NextResponse.json({ Message: "Success", status: 201 });
  } catch (error) {
    // If an error occurs during file writing, log the error and return a JSON response with a failure message and a 500 status code
    console.log("Error occurred ", error);
    return NextResponse.json({ Message: "Failed", status: 500 });
  }
};


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
  
  
  Usage
&lt;/h2&gt;

&lt;p&gt;Uploading a File&lt;br&gt;
To upload a file, make a POST request to the defined API endpoint with the file included in the request payload as a form data field named "file". The API handles the file processing and saves it to the server in the public/assets/ directory with a modified filename.&lt;/p&gt;

&lt;p&gt;Example using fetch in JavaScript:&lt;br&gt;
const fileInput = document.getElementById("fileInput"); // Replace with your HTML element ID&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

const file = fileInput.files[0];

const formData = new FormData();
formData.append("file", file);

fetch("/api/upload", {
  method: "POST",
  body: formData,
})
  .then(response =&amp;gt; response.json())
  .then(data =&amp;gt; console.log(data))
  .catch(error =&amp;gt; console.error(error));



&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
  
  
  Response
&lt;/h2&gt;

&lt;p&gt;The API returns JSON responses to indicate the success or failure of the file upload operation.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Success Response (HTTP Status Code: 201 Created)&lt;/strong&gt;&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

{
  "Message": "Success",
  "status": 201
}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Failure Response (HTTP Status Code: 500 Internal Server Error)&lt;/strong&gt;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

{
  "Message": "Failed",
  "status": 500
}




&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

</description>
      <category>nextjs</category>
      <category>fileupload</category>
      <category>api</category>
      <category>node</category>
    </item>
  </channel>
</rss>
