如何在 ReactJS 中使用 axios 將一個或多個檔案傳送到 API?
ReactJS 是一個前端庫,因此我們可以使用它來建立網頁。在即時應用程式中顯示資料是很自然的,並且後端管理它。因此,每當 React 需要在網頁上顯示資料時,它都會透過發出 API 呼叫來從後端獲取資料。
有時,我們可能需要將資料傳送到後端以將其儲存在資料庫中。例如,我們獲取了使用者的個人資料圖片,需要將其傳送到後端以將其儲存在資料庫中。
在許多情況下,我們需要使用 ReactJs 將單個或多個檔案傳送到後端。例如,某些剽竊檢查工具允許上傳多個檔案以檢查內容中的剽竊情況。
本教程將使用 axios 在 ReactJs 中將單個或多個檔案傳送到後端。
建立應用程式併發送多個檔案的步驟
這裡,我們將建立兩個應用程式。一個是 React 應用程式,我們將用於前端部分,另一個是 Node 應用程式,我們將用作後端。
建立 React 應用程式
步驟 1 – 使用以下命令在專案目錄中建立一個 React 應用程式。
npx create-react-app app-name
在上述命令中,app-name 是應用程式的名稱,使用者可以用任何名稱替換它。
步驟 2 – 現在,使用以下命令並在 React 應用程式中安裝 axios NPM 包。
npm i axios
步驟 3 – 建立一個可以處理多個檔案的輸入檔案。此外,建立一個提交按鈕,當用戶點選它時,它應該呼叫一個函式,該函式使用多個檔案向後端發出 POST 請求。
步驟 4 – 建立一個 uploadMultipleFiles() 函式,它可以使用 axios 發出 POST 請求。
uploadMultipleFiles() { axios({ url: "https://:8080/addFiles", method: "POST", data: { allFiles: files }, }) }
在上面的程式碼中,使用者可以觀察到我們使用了後端的端點並將“POST”作為方法的值來向後端發出 POST 請求。此外,我們在發出請求時傳遞了資料物件,我們可以在後端接收並操作這些檔案。
步驟 5 – 接下來,使用者可以將以下程式碼新增到應用程式的 App.js 檔案中。
import React from "react"; import axios from "axios"; class App extends React.Component { state = { allFiles: [], }; changeFileInput(event) { // using the setState method to set uploaded files to allFiles in the state object let files = event.target.files; this.setState({ allFiles: files }); } uploadMultipleFiles() { // get files from the state let uploadedFiles = this.state.allFiles; let files = []; // get the name of the files and push them to the files array //users can also get files content, convert it to blob format and send it to the backend for (let the file of uploadedFiles) { files.push({ name: file.name }); } axios({ url: "https://:8080/addFiles", // URL to make request method: "POST", // post method to send data data: { allFiles: files }, // attaching the files }) .then((res) => { // handle response console.log(res); }) .catch((err) => { // handle errors console.error(err); }); } render() { return ( <div> <h2> {" "} Using the <i> axios </i> to upload multiple files on NodeJs server.{" "} </h2> <input Type = "file" multiple // adding multiple attributes to allow users to upload multiple files. onChange = {(event) => this.changeFileInput(event)} /> <button onClick = {() => this.uploadMultipleFiles()}> Send Multiple Files to the server </button> </div> ); } } export default App;
在上面的程式碼中,我們建立了檔案輸入。每當使用者上傳多個檔案時,我們都會呼叫 changeFileInput() 函式,該函式將所有檔案設定為狀態物件中的 allFiles 變數。
當用戶點選按鈕時,它會呼叫 uplaodMultipleFiles() 函式,該函式從狀態中訪問所有檔案並建立檔案物件的陣列。但是,我們只在物件中添加了檔名,但使用者可以訪問檔案內容,將其轉換為 blob 物件,並將其新增到檔案物件中。
之後,我們使用 axios 向後端發出 POST 請求並將物件作為資料值傳遞。
步驟 6 – 作為最後一步,使用者需要使用以下命令執行應用程式。
npm start
建立 Node 應用程式
步驟 1 – 在終端中輸入以下命令以建立一個 Node 應用程式。
node init -y
步驟 2 – 現在,在 Node 專案中安裝所需的依賴項。使用者應在終端中輸入以下命令以在應用程式中安裝依賴項。
npm i express cors body-parser
我們將使用 express 建立伺服器,使用 cors 作為中介軟體,允許我們從前端到後端傳送 POST 請求。body-parse 將解析我們在從前端發出 POST 請求時傳遞的資料。
步驟 3 – 在 Node 應用程式中,使用以下程式碼設定伺服器。
var express = require("express"); var app = express(); app.listen(8080, function () { console.log("server started successfully"); });
步驟 4 – 現在,在“/addFiles”路由上處理 POST 請求。在回撥函式中,使用以下程式碼從主體獲取檔案。
app.post("/addFiles", function (req, res) { // get files from the body here });
步驟 5 – 使用者可以將以下完整程式碼新增到 server.js 檔案中。如果專案中不存在 server.js 檔案,使用者可以建立一個名為 server.js 的檔案。
// Importing the required and installed modules var express = require("express"); var cors = require("cors"); var app = express(); const bodyParser = require("body-parser"); // using middleware with app app.use(cors()); app.use(bodyParser.urlencoded({ extended: false })); app.use(bodyParser.json()); // allow users to make a post request. app.post("/addFiles", function (req, res) { let allFiles = req.body; console.log(allFiles); }); // Allowing the app to listen on port 8080 app.listen(8080, function () { console.log("server started successfully"); });
在上面的程式碼中,我們匯入了所需的庫。之後,我們在 Node 應用程式中設定了 express 伺服器。此外,我們使用了 body-parse 從主體中提取資料,並在 express 應用程式中使用 cors 作為中介軟體。
之後,我們建立了處理檔案的端點並在控制檯中列印所有檔案。
步驟 6 – 我們已準備好處理 Node 應用程式上的 POST 請求。使用者需要透過在終端上執行以下命令來執行 Node 應用程式。
node server.js
輸出
現在,使用者有兩個應用程式在不同的埠上執行。使用者可以在下圖中看到 React 應用程式的輸出。

當我們在網頁上上傳多個檔案時,Node 應用程式會在控制檯中列印所有檔名,如下面的影像所示。

我們學習瞭如何使用 axios POST 請求將多個檔案傳送到後端。但是,在本教程中我們只發送了檔名,但使用者也可以傳送檔案內容和更新日期等。