前端 Vue.js 使用 Axios 提交多个文件

以下代码展示如何使用 Vue.js 和 Axios 库提交多个文件到后端:

let formData = new FormData();

for(let i=0; i<files.length; i++) {
  formData.append('files[]', files[i]);
}

axios.post('/upload', formData, {
  headers: {
    'Content-Type': 'multipart/form-data'
  }
}).then(response => {
  console.log(response);
}).catch(error => {
  console.log(error);
});

其中,files 是一个文件数组,可以通过 <input type="file" multiple> 获取到。

后端 Koa.js 实现上传文件接口

以下代码展示使用 Koa.js 框架实现一个接收和处理上传文件的 API 接口:

const Koa = require('koa');
const koaBody = require('koa-body');
const fs = require('fs');
const path = require('path');

const app = new Koa();

app.use(koaBody({
  multipart: true,
  formidable: {
    uploadDir: path.join(__dirname, 'uploads'),
    keepExtensions: true,
    maxFileSize: 200 * 1024 * 1024 // 200MB
  }
}));

app.use(async ctx => {
  const files = ctx.request.files.files;

  if(!files || !Array.isArray(files)) {
    ctx.throw(400, 'No files were uploaded.');
  }

  const result = [];

  for(let i=0; i<files.length; i++) {
    const file = files[i];
    const filePath = file.path;

    result.push({
      name: file.name,
      type: file.type,
      size: file.size,
      path: filePath.replace(/\\/g, '/')
    });
  }

  ctx.body = { success: true, data: result };
});

app.listen(3000, () => console.log('Server is running on http://localhost:3000'));

其中,koa-body 中间件用于解析上传的文件,uploadDir 指定上传文件的保存路径,keepExtensions 指定是否保留文件的扩展名,maxFileSize 指定上传文件的最大大小。在处理上传文件的路由中,首先判断是否有文件上传,然后遍历所有上传的文件,将文件信息保存到数组中并返回给前端。

Vue.js + Axios 多文件上传 - Koa.js 文件接收与处理

原文地址: https://www.cveoy.top/t/topic/mCH1 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录