欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

React+react-dropzone+node.js实现图片上传的示例代码

程序员文章站 2022-04-29 08:09:55
本文将会用typescript+react+react-dropzone+express.js实现前后端上传图片。当然是用typescript需要提前下载相应的模块,在这里...

本文将会用typescript+react+react-dropzone+express.js实现前后端上传图片。当然是用typescript需要提前下载相应的模块,在这里就不依依介绍了。

第一步,配置tsconfig.js

  "compileroptions": { 
      "outdir": "./public/", 
      "sourcemap": true, 
      "noimplicitany": true, 
      "module": "commonjs", 
      "target": "es5", 
      "jsx": "react" ,
      "noimplicitany": false,
      "suppressimplicitanyindexerrors": true
  },
  "files": [ "./views/home/main.tsx" ],
  "exclude": [
    "node_modules"
  ]
}

2.配置webpack

var path = require('path');
var webpack = require('webpack');
var extracttextplugin = require("extract-text-webpack-plugin");
var htmlwebpackplugin = require('html-webpack-plugin');
var title = {
  home: '首页',
}
module.exports = {
  entry: {
    home: [
      'babel-polyfill',
      './views/home/main.tsx'
    ],
    common: ['react','babel-polyfill']
  },
  output: {
    path: path.join(__dirname, 'views/wap'),
    filename: '[name].js',
    chunkfilename: '[id].build.js?[chunkhash]',
    publicpath: '/views/wap/',
  },
  module: {
    loaders: [
      { 
        test: /\.tsx?$/, 
        loader: 'ts-loader' 
      },
      {
        test: /\.(less|css)$/,
        loader: extracttextplugin.extract('style', 'css!less'),
      },
      {     
       test:/\.(js|jsx)?$/,
       loader:'babel',
       exclude:/node_modules/,
       query:{compact:false,presets:['es2015','react','stage-0','stage-1','stage-2']}
      },
      {
        test: /\.(png|jpg|gif)?$/,
        loaders: ['url?limit=8192&name=[name]_[sha512:hash:base64:7].[ext]'],
      },
      {
        test: /\.(eot|woff|ttf|svg)$/,
        loader: 'file?limit=81920&name=[name]_[sha512:hash:base64:7].[ext]'
      },
    ]
  },
  resolve: {
    root: ['node_modules'],
    extensions: ['', '.js', '.jsx', '.html', '.json','.ts', '.tsx'],
    modulesdirectories: ['node_modules'],
    alias: {}
  },
  externals: {},
  plugins: [
    new webpack.defineplugin({
      'process.env.node_env': '"production"'
    }),
    new webpack.hotmodulereplacementplugin(),
    new extracttextplugin('[name].[contenthash:20].css'),
    new webpack.optimize.uglifyjsplugin({
      compress: {warnings: false}
    }),
    new webpack.optimize.commonschunkplugin('common', 'common.js'),
      new htmlwebpackplugin(
      {
         title: "",
         template: path.join(path.resolve(__dirname),'views/wap/myapp.html'), //模板文件
         inject:'body',
         hash:true,  //为静态资源生成hash值
         minify:{  //压缩html文件
          removecomments:false,  //移除html中的注释
          collapsewhitespace:false  //删除空白符与换行符
         }
      }
      )
  ]
};

3.react-dropzone

import * as dropzone from 'react-dropzone';

<dropzone  accept="image/jpeg, image/png"
      ondrop={(accepted, rejected) => { this.setstate({ accepted, rejected });this.drop(accepted[0].preview) }}
      style={{width:"100%",height:"120px",background:"#f2f2f2","padding-top":'90px',"cursor":"pointer","box-sizing":"content-box"}} >
</dropzone>

accept:表示图片的接受类型

ondrop代表图片加载以后触发

accepted:表示加载图片成功后相关信息,打印出来如下:

React+react-dropzone+node.js实现图片上传的示例代码

rejected:表示加载图片失败后,相关信息:

React+react-dropzone+node.js实现图片上传的示例代码

4.图片处理、上传

新建一个drop方法在触发ondrop后。

drop(src : any) : any{
    const that = this;
    let img = src;
    let image = new image();
    image.crossorigin = 'anonymous';
    image.src = img;
    image.onload = function(){
      let base64 = that.getbase64image(image);
      that.uploadimg({imgdata:base64})
    }
}

在这里我们使用base64传递,所以我们需要把图片转成base64,定义getbase64image处理

getbase64image(img :any) : string {
    let canvas = document.createelement("canvas");
    canvas.width = img.width;
    canvas.height = img.height;
    let ctx = canvas.getcontext("2d");
    ctx.drawimage(img, 0, 0, img.width, img.height);
    let ext = img.src.substring(img.src.lastindexof(".")+1).tolowercase();
    let dataurl = canvas.todataurl("image/"+ext);
    return dataurl;
}

最终返回的是处理后图片的地址,然后上传

async uploadimg(params : object) : promise<any>{
    let res = await axios.post('http://localhost:3000/uploadimg',params);
}

5.node部分

router/index.js

var express = require('express');
var router = express.router();
var rf = require('fs');
var setimg = require('./controller/uploadimg');
var setimg = new setimg;
router.post('/uploadimg',setimg.setuploadimg);
module.exports = router;

./controller/uploadimg.js

var rf = require('fs');
class setimg {
  setuploadimg(req, res, next) {
    let imgdata = req.body.imgdata;
    let base64data = imgdata.replace(/^data:image\/\w+;base64,/, "");
    let databuffer = new buffer(base64data, 'base64');
    let timer = number( new date() );
    rf.writefile("views/images/artcover"+timer+".png",databuffer, function(err) {
      if(err) {
       res.json({"code":400,"verson":false,"msg":err});
      }else {
       res.json({"code":100,"verson":true,"url":"views/src/common/images/artcover/"+timer+".png"});
      }
    });
  }
}
module.exports = setimg;

拿到图片后先进行格式转换,然后将图片写入到本地,返回图片路径。

import * as react from 'react';
import * as reactdom  from 'react-dom';

import * as dropzone from 'react-dropzone';
import * as axios from 'axios';

import './main.less';

declare var document;
declare var image;
class imgupload extends react.component<any,any> {
  constructor(){
    super()
    this.state = {
     accepted: [],
     rejected: []
    }
  }
  public drop(src : any) : any{
    const that = this;
    let img = src;
    let image = new image();
    image.crossorigin = 'anonymous';
    image.src = img;
    image.onload = function(){
      let base64 = that.getbase64image(image);
      console.log(base64)
      that.uploadimg({imgdata:base64})
    }
  }
  //转base64
  public getbase64image(img :any) : string {
    let canvas = document.createelement("canvas");
    canvas.width = img.width;
    canvas.height = img.height;
    let ctx = canvas.getcontext("2d");
    ctx.drawimage(img, 0, 0, img.width, img.height);
    let ext = img.src.substring(img.src.lastindexof(".")+1).tolowercase();
    let dataurl = canvas.todataurl("image/"+ext);
    return dataurl;
  }
  public async uploadimg(params : object) : promise<any>{
    let res = await axios.post('http://localhost:3000/uploadimg',params);

  }
  render(){
    const that = this;
    let imgs;
    if(this.state.accepted.length > 0){
      imgs = (
        <ul>
          {this.state.accepted.map( (f) => {
            return <img key={f.name} src={f.preview} />
          })}
        </ul>
      )
    }
    return (
      <div>
        <div classname="wrap">
          <dropzone
          accept="image/jpeg, image/png"
          ondrop={(accepted, rejected) => { console.log(accepted);console.log(rejected);this.setstate({ accepted, rejected });this.drop(accepted[0].preview) }}
          style={{width:"100%",height:"120px",background:"#f2f2f2","padding-top":'90px',"cursor":"pointer","box-sizing":"content-box"}}
           >
            <p classname="upload">请添加主题图片</p>
          </dropzone>
        </div>
        <div classname="show">{imgs}  
        </div> 
      </div>
      
    )
  }

}
reactdom.render(
  <imgupload />,
  document.getelementbyid('app')
)

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。