1. Koa back-end operation

1. Install koA-body

npm install koa-body --save
Copy the code

The koa-body configuration is then performed

Since koA-BodyParser was previously installed, koA-body contains the parsed part of koA-BodyParser, and there is no need to install KoA-multer. If koA-BodyParser is not commented out, A server error BadRequestError: Request aborted error occurs when the front end calls another request interface

App.js is configured as follows

const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const serve = require("koa-static");
const logger = require('koa-logger')
const cors = require("koa2-cors");
const koaBody = require("koa-body");
const index = require('./routes/index')
const users = require('./routes/users')
const publics = require("./routes/publics");
const path = require("path"); 
// error handler
onerror(app)
// 1. Static resource service: specifies the root directory for external access
app.use(serve(path.join(__dirname, '/public')));

// middlewares
/ * app. Use (bodyparser ({- commented this middleware enableTypes: [' json ', 'form', 'text']})) * /
app.use(
  koaBody({
    enableTypes: ["json"."form"."text"].multipart: true.strict: false.formidable: {
      maxFileSize: 5 * 1024 * 1024.// set the maximum file size to 5M by default
      uploadDir: path.join(__dirname, "public/upload/"), // Set the directory for uploading files
      keepExtensions: true.// Keep the file extension}})); app.use(json()) app.use(logger()) app.use(require('koa-static')(__dirname + '/public'))

app.use(views(__dirname + '/views', {
  extension: 'pug'
}))
// logger
app.use(async (ctx, next) => {
  const start = new Date(a)await next()
  const ms = new Date() - start
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)})// Allow cross-domain
app.use(cors())
// routes
app.use(index.routes(), index.allowedMethods())
app.use(users.routes(), users.allowedMethods())
app.use(publics.routes(), publics.allowedMethods())
// error-handling
app.on('error'.(err, ctx) = > {
  console.error('server error', err, ctx)
});

module.exports = app
Copy the code

2. Koa back-end upload interface

const path = require("path"); // Image path
class PublicControler {
  static async uplod(ctx) {
    const file = ctx.request.files.file
    const basename = path.basename(file.path)
    const size = (file.size/1024) /1024-- Picture sizetry{
       ctx.response.status = 200;
       if(size>5){
          ctx.body = {
             code: 201.message: "Image uploaded over 5M"}; }else{
         ctx.body = {
           code: 200.data: {
             path: file.path, -- returns the local file pathurl: `${ctx.origin}/public/upload/${basename}`Return ctx.origin (current domain name)},message: "Picture uploaded successfully"}; }}catch(error){
       ctx.response.status = 500;
       ctx.body = {
         code: 500.message: "Upload error"}; }}}module.exports = PublicControler;
Copy the code

Since multiple file uploads are enabled by default, ctx.request.files is an object,

The name=photo attribute of the form is used as the key of the object, and the value is a File object with the following useful fields:

Parameter names describe
size The file size
path Directory for uploading files
name Original file name
type The file type
lastModifiedDate Last updated

3. Configuration of koA-body

1) Basic parameters of KOA-body

Parameter names describe type The default value
patchNode Type the request body to the nativenode.jsctx.reqIn the Boolean false
patchKoa Type the request body into koA’sctx.request Boolean true
jsonLimit Size limits for JSON data bodies String / Integer 1mb
formLimit Limit the size of the form request body String / Integer 56kb
textLimit limittext bodyThe size of the String / Integer 56kb
encoding The default encoding of the form String utf-8
multipart Whether multipart-formdate forms are supported Boolean false
urlencoded Whether to supporturlencodedThe form of Boolean true
text Whether the parsingtext/plainThe form of Boolean true
json Whether the parsingjsonRequest body Boolean true
jsonStrict Whether to usejsonStrict mode,true Will only deal with arrays and objects Boolean true
formidable Configure more aboutmultipartThe option to Object {}
onError Error handling Function function(){}
stict Strict mode, not parsed after enabledGET, HEAD, DELETE Boolean true

2) Configuration parameters of formidable

Parameter names describe type The default value
maxFields Limit the number of fields Integer 1000
maxFieldsSize Limits the maximum size of a field Integer 2 * 1024 * 1024
uploadDir File upload folder String os.tmpDir()
keepExtensions Keep the original file suffix Boolean false
hash If you want to calculate the filehash, you can selectmd5/sha1 String false
multipart Whether to upload multiple files Boolean true
onFileBegin Some Settings before uploading files Function function(name,file){}

React front-end calls

 <Upload
     name="file"
     action={`The ${this.api.login.uplod}`} -- upload address beforeUpload={this.beforeUpload}
     className="uplod"
     showUploadList={false} -- do not display list ><Button icon="upload">To upload pictures</Button>
     </Upload>
Copy the code

Interface call

 beforeUpload = (e) = > {
    const size = (e.size/1024) /1024
    if(e.type ! ="image/png"&& e.type ! ="image/jpeg"&&e.type! ="image/jpg") {
      message.warning("Wrong format");
      return false;
    }else{
      const formData = new FormData();  --用表单形式上传
      formData.append("file", e);
      if(size>5){
        message.warning('Picture uploaded over 5M, please re-upload');
      }else{
        this.post(`The ${this.api.login.uplod}`, formData)
          .then((res) = > {
            if (res.code == 200) {
              message.success(res.message);
              this.setState({
                imgUrl: res.data.path,
              });
            } else {
              message.warning(res.message);
            }
          })
          .catch((res) = >{ message.warning(res.message); }); }}};Copy the code