zoukankan      html  css  js  c++  java
  • koa2实现文件上传服务

    使用方法

    方法一:

    使用中间介 koa-body

    方法二:

    自己写个借口去接收数据流并保存

    方法三:

    使用 koa-body 接受文件,自己写个接口做文件保存或处理等操作

    这里简单记录方法三

    app.js

    const Koa = require('koa')
    const koaBody = require()
    
    const app = new Koa()
    app.use(koaBody({
      multipart: reue,  // 支持表单上传
      formidable: {
        maxFileSize: 10 * 1024 * 1024, // 修改文件大小限制,默认位2M
      }
    }))

    api.js

    const router = require('koa-router')()
    const uploadimg = require('./uploadImg')
    
    router.prefix('/api')
    
    router.post('/uploadImg', async function(ctx, next) {
      const imgUrl = await uploadimg(ctx);
      if (imgUrl) {
        ctx.body = {
          data: imgUrl,
          message: '文件上传成功',
          code: '0',
        }
      } else {
        ctx.body = {
          data: imgUrl,
          message: '文件上传失败',
          code: '1',
        }
      }
      
    })
    
    module.exports = router
    uploadImg.js
    const path = require('path');
    const fs = require('fs');
    
    
    const uploadimg = (ctx) => {
      console.log(JSON.stringify(ctx.request, null, ' '));
      let remotefilePath = null;
      if (ctx.request.files['file']) {
        // 创建可读流
        const reader = fs.createReadStream(ctx.request.files['file']['path']);
        let filePath = `${path.resolve(__dirname, '../../publicPath/images')}/${ctx.request.files['file']['name']}`;
        remotefilePath = `http://yourServerHostAndPath/images/${ctx.request.files['file']['name']}`;
        // 创建可写流
        const upStream = fs.createWriteStream(filePath);
        // 可读流通过管道写入可写流
        reader.pipe(upStream);
      }
      return remotefilePath;
    }
    
    module.exports = uploadimg;

    在前端中上传文件

    upLoadFile.js

    const upload = (file) => {
    
      const formData = new FormData();
      formData.append('file', file);
    
      return fetch({
        method: 'post',
        body: formData,
      })
    }

    如上即可,注意的地方,使用 fetch 的话不用刻意去设置 header 的 Content-Type 属性,fetch 会自动给你设置好的,如果你设置的不对还可能导致上传失败。

  • 相关阅读:
    POJ 1330 Nearest Common Ancestors(LCA Tarjan算法)
    LCA 最近公共祖先 (模板)
    线段树,最大值查询位置
    带权并查集
    转负二进制
    UVA 11437 Triangle Fun
    UVA 11488 Hyper Prefix Sets (字典树)
    UVALive 3295 Counting Triangles
    POJ 2752 Seek the Name, Seek the Fame (KMP)
    UVA 11584 Partitioning by Palindromes (字符串区间dp)
  • 原文地址:https://www.cnblogs.com/YMaster/p/10880157.html
Copyright © 2011-2022 走看看