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");
});


在这里插入图片描述



<!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>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

lionliu0519

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值