• React(1702H)文件上传和分页查找


    1.上传

    dom:

                <div className="m-upload-input-wrap">
                  <input type="file" value="" onChange={this.handleUpload.bind(this)}/>
                </div>

     接口:

      handleUpload(e) {
        const data = new FormData();
        data.append('file', e.target.files[0]);
        const params = `/upload`
        axios({
            method: 'post',
            data: data, 
            url: params,
            timeout: 1000 * 60 * 60 * 8
          })
          .then((res) => {
            console.log(res)      
            this.getUploadList()     
          })
          .catch((err) => {
            console.log(err)          
          })
      },

    2.显示列表(antd table)

    dom:

                <div>
                  <Table 
                    columns={columns} 
                    dataSource={list} 
                    rowKey="uid"
                    pagination={ total > 10 ? {
                      total: total,
                      current: current,
                      pageSize: 10,
                      onChange: this.handlePage.bind(this)
                    } : false}></Table>
                </div>

    columns:

      renderColumns () {
        return [
          {
            title: '图片',
            dataIndex: 'path',
            render: (text, record, index) => {
              return <span><img src={text} className="m-upload-img"></img></span>
            }
          },       
          {
            title: '文件名',
            dataIndex: 'originalname',
            key: 'originalname',
          },   
          {
            title: '操作',
            render: (text, record, index) => {
              return <div>
                <Button onClick={this.handleCopy.bind(this, record)} >复制链接</Button>
              </div>
            }
          }      
        ]
      },

    获取列表:

      getUploadList() {
        Api.getUploadList(`?page=1&size=10`).then((res) => {
          console.log(res)
          if (res.code === keyCode.SUCCESS) {
            this.setState({
              list: res.data.list,
              current: 1,
              total: res.data.total
            })
          }
        })
      },

    分页:

      handlePage(current) {
        Api.getUploadList(`?page=${current}&size=10`).then((res) => {
          console.log(res)
          if (res.code === keyCode.SUCCESS) {
            this.setState({
              list: res.data.list,
              current: current,
              total: res.data.total
            })
          }
        })    
      }

    3.后端接口

    用到的npm包:

    const multer = require('multer')

    配置:

    var storage = multer.diskStorage({
      destination: function (req, file, cb) {
        // 接收到文件后输出的保存路径(若不存在则需要创建)
        cb(null, 'public/images/');
      },
      filename: function (req, file, cb) {
        // 将保存文件名设置为 时间戳 + 文件原始名,比如 151342376785-123.jpg
        cb(null, Date.now() + "-" + file.originalname);
      }
    });
    var upload = multer({ storage: storage });

    参考链接:https://www.npmjs.com/package/multer

    上传接口:

    //文件上传
    app.post('/upload', upload.single('file'), async function (req, res, next) {
      var file = req.file;
      console.log('文件类型:%s', file.mimetype);
      console.log('原始文件名:%s', file.originalname);
      console.log('文件大小:%s', file.size);
      console.log('文件保存路径:%s', file.path);
      console.log(file)
      let uid = getID(10)
      let createTime = new Date().getTime()
      const data = await uploadAdd(
        uid,
        `http://localhost:8888/images/${file.filename}`,
        file.originalname,
        createTime)
      if (data) {
        res.send(({
          code: 200,
          data: file,
          message: '上传成功'
        }))
      } else {
        res.send(({
          code: 400,
          data: file,
          message: '上传失败'
        }))
      }
    })

    分页查找:

    //获取上传列表
    app.get('/upload/list', async function (req, res) {
      let { page, size } = req.query
      start = (page - 1) * size
      const data = await getUploadList(start, size)
      console.log(data)
      let token = req.headers['token']
      let auth = getTokenAuth(token)
      if (auth) {
        res.send(({
          code: 200,
          data: data,
          message: '上传文件列表'
        }))
      } else {
        deleteTokenHistory(token)
        res.send(({
          code: 403,
          message: '无权限'
        }))
      }
    })

    sql语句建表:

    DROP TABLE IF EXISTS `upload`;
    CREATE TABLE `upload` (
      `uid` varchar(100) COLLATE utf8_unicode_ci NOT NULL COMMENT 'ID',
      `path` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '路径',
    	`originalname` varchar(1000) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '原始文件名',
      `create_time` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '创建时间',
      PRIMARY KEY (`uid`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
  • 相关阅读:
    安装 kubenetes-dashboard
    使用kubeadm在Centos7上部署kubernetes1.21.1
    批量重命名
    is_valid重写。返回数据格式统一
    django-序列化参数为空报错问题
    单文件日志测试
    文本、目录 空间清理问题
    数仓数据
    滑动验证码(无原图片处理)
    鸟哥私房菜基础篇
  • 原文地址:https://www.cnblogs.com/xutongbao/p/11915677.html
Copyright © 2020-2023  润新知