koa2实现文件上传接口

{
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node app.js",
    "dev": "nodemon app.js"
  },
  "dependencies": {
    "koa": "^2.14.2",
    "koa-body": "^6.0.1",
    "koa-router": "^12.0.0",
    "koa2-cors": "^2.0.6",
    "nodemon": "^2.0.22"
  }
}

const Koa = require("koa");
const Router = require("koa-router");
const { koaBody } = require("koa-body");
const cors = require("koa2-cors");
const path = require("path");

const app = new Koa();
const router = new Router();

// Enable CORS
app.use(cors());

// Set up koaBody middleware to handle file uploads
app.use(
  koaBody({
    multipart: true,
    formidable: {
      uploadDir: path.join(__dirname, "uploads"), // Directory to store uploaded files
      keepExtensions: true, // Keep the original file extensions
    },
  })
);

// Define a route to handle file uploads
router.post("/upload", async (ctx) => {
  const file = ctx.request.files.file; // Access the uploaded file

  // Handle the uploaded file as needed (e.g., save it to a database or process it further)
  console.log(file);

  ctx.body = "File uploaded successfully";
});

app.use(router.routes());
app.listen(3000, () => {
  console.log("Server running on http://localhost:3000");
});


koa2实现文件上传接口_第1张图片



<!DOCTYPE html>
<html>
  <head>
    <title>File Upload Simulation</title>
  </head>
  <body>
    <h1>File Upload Simulation</h1>
    <form id="uploadForm" enctype="multipart/form-data">
      <input type="file" id="fileInput" name="file" />
      <button type="submit">Upload</button>
    </form>

    <script>
      document
        .getElementById("uploadForm")
        .addEventListener("submit", function (event) {
          event.preventDefault(); // Prevent form submission

          const fileInput = document.getElementById("fileInput");
          const file = fileInput.files[0];

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

          // Send the form data via AJAX (you can use fetch() or XMLHttpRequest)
          const xhr = new XMLHttpRequest();
          xhr.open("POST", "http://localhost:3000/upload"); // Adjust the server URL accordingly
          xhr.onload = function () {
            if (xhr.status === 200) {
              console.log("File uploaded successfully");
            } else {
              console.error("Error uploading file:", xhr.statusText);
            }
          };
          xhr.send(formData);
        });
    </script>
  </body>
</html>

你可能感兴趣的:(javascript,前端,html)