logo
  • Guide
  • Config
  • Plugin
  • API
  • Examples
  • Community
  • Modern.js 2.x Docs
  • English
    • 简体中文
    • English
    • Start
      Introduction
      Quick Start
      Upgrading
      Glossary
      Tech Stack
      Core Concept
      Page Entry
      Build Engine
      Web Server
      Basic Features
      Routes
      Routing
      Config Routes
      Data Solution
      Data Fetching
      Data Writing
      Data Caching
      Rendering
      Server-Side Rendering
      Streaming SSR
      Rendering Cache
      Static Site Generation
      Render Preprocessing
      Styling
      Styling
      Use CSS Modules
      Using CSS-in-JS
      Using Tailwind CSS
      HTML Template
      Import Static Assets
      Import JSON Files
      Import SVG Assets
      Import Wasm Assets
      Debug
      Data Mocking
      Network Proxy
      Using Rsdoctor
      Using Storybook
      Testing
      Playwright
      Vitest
      Jest
      Cypress
      Path Alias
      Environment Variables
      Output Files
      Deploy Application
      Advanced Features
      Using Rspack
      Using BFF
      Basic Usage
      Runtime Framework
      Extend BFF Server
      Extend Request SDK
      File Upload
      Cross-Project Invocation
      Optimize Page Performance
      Code Splitting
      Inline Static Assets
      Bundle Size Optimization
      React Compiler
      Improve Build Performance
      Browser Compatibility
      Low-Level Tools
      Source Code Build Mode
      Server Monitor
      Monitors
      Logs Events
      Metrics Events
      Internationalization
      Basic Concepts
      Quick Start
      Configuration
      Locale Detection
      Resource Loading
      Routing Integration
      API Reference
      Advanced Usage
      Best Practices
      Custom Web Server
      Topic Detail
      Module Federation
      Introduction
      Getting Started
      Application-Level Modules
      Server-Side Rendering
      Deployment
      Integrating Internationalization
      FAQ
      Dependencies FAQ
      CLI FAQ
      Build FAQ
      HMR FAQ
      Deprecated
      📝 Edit this page
      Previous pageExtend Request SDKNext pageCross-Project Invocation

      #File Upload

      BFF combined with runtime framework provides file upload capabilities, supporting integrated calls and pure function manual calls.

      #BFF Function

      First, create the api/lambda/upload.ts file:

      api/lambda/upload.ts
      export const post = async ({ formData }: {formData: Record<string, any>}) => {
        console.info('formData:', formData);
        // do somethings
        return {
          data: {
            code: 0,
          },
        };
      };
      Tip

      The formData parameter in the interface processing function can access files uploaded from the client side. It is an Object where the keys correspond to the field names used during the upload.

      #Integrated Calling

      Next, directly import and call the function in src/routes/upload/page.tsx:

      routes/upload/page.tsx
      import { upload } from '@api/upload';
      import React from 'react';
      
      export default (): JSX.Element => {
        const [file, setFile] = React.useState<FileList | null>();
      
        const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
          setFile(e.target.files);
        };
      
        const handleUpload = () => {
          if (!file) {
            return;
          }
          upload({
            files: {
              images: file,
            },
          });
        };
      
        return (
          <div>
            <input multiple type="file" onChange={handleChange} />
            <button onClick={handleUpload}>upload</button>
          </div>
        );
      };
      Tip

      Note: The input type must be { formData: FormData } for the upload to succeed.

      #Manual Calling

      You can manually upload files using the fetch API, when calling fetch, set the body as FormData type and submit a post request.

      routes/upload/page.tsx
      import React from 'react';
      
      export default (): JSX.Element => {
        const [file, setFile] = React.useState<FileList | null>();
      
        const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
          setFile(e.target.files);
        };
      
        const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
          e.preventDefault();
          const formData = new FormData();
          if (file) {
            for (let i = 0; i < file.length; i++) {
              formData.append('images', file[i]);
            }
            await fetch('/api/upload', {
              method: 'POST',
              body: formData,
            });
          }
        };
      
        return (
          <form onSubmit={handleSubmit}>
            <input multiple type="file" onChange={handleChange} />
            <button type="submit">upload</button>
          </form>
        );
      };