input上传图片预览

前端代码示例





  
  图片上传



  
上传

js提交

下面是后端nodejs代码示例
前端上传文件,后端接收并将图片地址返回给前端

const Koa = require('koa')
const app = new Koa()
const serve = require('koa-static')
const koaBody = require('koa-body')
const {resolve}=require('path')
const cors = require('@koa/cors')
const {
  initRouter
} = require('./routes')

app.use(koaBody({
  multipart:true,
  formidable: {
        uploadDir: resolve(__dirname, 'public/uploads')
    }
}))
app.use(cors())
async function start() {
  initRouter(app)
  app.use(serve(__dirname + '/public'))
}
start()
app.listen(3000, () => {
  console.log('sever listen 3000')
})

下面是处理文件上传的路由文件
前端单个字段可以上传多张图片,多张图片是返回对象是一个数组,单张是返回是一个对象

const Router = require('koa-router')
const fs = require('fs')
const path = require('path')
const router = new Router({
  prefix: '/api'
})
router.post('/upload', async (ctx, next) => {
  let fileObj = {}
  let files = ctx.request.files
  for (let i in ctx.request.files) {
    let file = ctx.request.files[i]
    let isSingle = false
    if (!Array.isArray(file)) {
      file = [file]
      isSingle = true
    }
    for (let j = 0; j < file.length; j++) {
      let singleRes = resolveSingleFile(file[j])
      if (singleRes) {
        // 单个文件直接赋值
        if (isSingle) {
          fileObj[i] = singleRes
          break
        } else if (!isSingle && !fileObj[i]) { // 如果是多个文件并且fileObj[i]还没有被赋值
          fileObj[i] = []
        }
        fileObj[i].push(singleRes)
      }
    }
  }
  ctx.body = {
    status: 1,
    data: fileObj
  }
})

function deleteUploadFile(filepath) {
  fs.unlink(filepath, function(err) {
    if (err) {
      console.log(err)
    }
  })
}

function resolveSingleFile(file) {
  let fname = file.name
  let fpath = file.path
  let res = {}
  if (file.size && file.path) {
    let extArr = fname.split('.')
    let ext = extArr[extArr.length - 1]
    let newPath = fpath + '.' + ext
    fs.renameSync(fpath, newPath)
    res.name = fname
    res.url = `http://localhost:3000/uploads/${ path.basename(newPath)}`
  } else {
    // 路径没找到直接返回
    if (!file.path) {
      return
    }
    // 文件大小为0直接删除
    deleteUploadFile(file.path)
  }
  return res
}
module.exports = {
  initRouter: function(app) {
    app
      .use(router.routes())
      .use(router.allowedMethods())
  }
}

返回格式示例

 {
  "status": 1,
  "data": {
    "file": { "name":"...","url":"..."},
    "file1":[ { "name":"...","url":"..."}]
  }
}

你可能感兴趣的:(input上传图片预览)