随手写系列--koa2搭建文件上传文件/获取文件--node动静资源分离

138 阅读1分钟

大概思路:

客户端--负责上传下载文件

node端--负责保存文件和提交用户信息和文件名给接口进行保存

接口端--保存文件名和对象的用户信息挂钩

--直接上代码 库包: koa koa-router koa-body代替koa-bodyparser/koa-multer koa2-cors--避免跨域 koa-static--指定静态资源 request--调用请求

//server端代码
const Koa = require('koa')
const path = require('path')
const Router = require('koa-router')
const koaBody = require('koa-body');
const fs = require('fs')
const cors = require('koa2-cors');
const static = require("koa-static");
const request=require('request')
const app = new Koa()
const router = new Router()
app.use(static(__dirname + "uploads"));
app.use(static(__dirname + "static"));
app.use(static(__dirname + "public"));
app.use(cors());
app.use(koaBody({
    multipart: true,
    formidable: {
        //上传文件存储目录
        uploadDir: path.join(__dirname, `/uploads/`),
        //允许保留后缀名
        keepExtensions: true,
        multipart: true,
        onFileBegin: (name, file) => {
            var pathArr = file.path.split("\\uploads\\")
            file.path = pathArr[0] + "\\uploads\\" + file.name
        }
    }
})
)
router.post('/download', async (ctx, next) => {
    let filename = 'test.js'
    ctx.set('content-type', 'application/octet-stream');
    const filePath = path.join(__dirname + '/uploads/', filename);
    let readStream = fs.createReadStream(filePath, 'utf-8');
    ctx.body = readStream
})
router.post('/upload', async (ctx, next) => {
    let fileName = ctx.request.files.file.name
    let url="http://localhost:3001/background"
    let requestData={
        fileName:"上传后台接口 "+fileName
    }
    request({
        url,
        method:"POST",
        json:true,
        headers:{
            "content-type":"application/json"
        },
        body:{
            data:JSON.stringify(requestData)
        }
    },(err,res,body)=>{
        if (!err && res.statusCode == 200) {
            console.log(body) // 请求成功的处理逻辑
        }
    })
})
router.post('/background',async(ctx,next)=>{
    console.log(ctx.request.body);
})


app.use(router.routes()).use(router.allowedMethods())
app.listen(3001)

//客户端代码--react
import React from 'react'
import axios from 'axios'
class MyEditor extends React.Component {
  constructor(props) {
    super(props)
    this.handleFileFn = this.handleFileFn.bind(this)
    this.getFileFn=this.getFileFn.bind(this)
  }

  handleFileFn(event){
    let files=event.target.files
    console.log(event,event.target.files,files[0]);
    let form =new FormData()
    form.append('file',files[0])
    const config={
      headers:{
        "Content-type":"multipart/form-data"
      }
    }
    axios.post('http://localhost:3001/upload',form,config)
  }
  getFileFn(){
    let fileName='test.js'
    axios.post('http://localhost:3001/download',{
      fileName:fileName
    }).then((res)=>{
      console.log(res.data);

    })
  }
  render() {
    return (
      <div className='contain'>
        <input type={'file'} onChange={this.handleFileFn}></input>
        <button onClick={this.getFileFn}>获取文件</button>
      </div>
    )
  }
}

export default MyEditor