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


Posted in Javascript onAugust 23, 2017

本文将会用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')
)

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

Javascript 相关文章推荐
用 JSON 处理缓存
Apr 27 Javascript
解决遍历时Array.indexOf产生的性能问题
Jul 03 Javascript
jquery ajax实现下拉框三级无刷新联动,且保存保持选中值状态
Oct 29 Javascript
javascript实现回车键提交表单方法总结
Jan 10 Javascript
JS+CSS实现可拖拽的漂亮圆角特效弹出层完整实例
Feb 13 Javascript
jQuery中的ready函数与window.onload谁先执行
Jun 21 Javascript
javascript 面向对象function详解及实例代码
Feb 28 Javascript
详解Vue中watch的详细用法
Nov 28 Javascript
Vue实现table上下移动功能示例
Feb 21 Javascript
在 Vue 中编写 SVG 图标组件的方法
Feb 24 Javascript
javascript实现贪吃蛇小练习
Jul 05 Javascript
解决vue elementUI 使用el-select 时 change事件的触发问题
Nov 17 Vue.js
深入理解React中何时使用箭头函数
Aug 23 #Javascript
自定义类似于jQuery UI Selectable 的Vue指令v-selectable
Aug 23 #jQuery
JS数组交集、并集、差集的示例代码
Aug 23 #Javascript
关于Vue实现组件信息的缓存问题
Aug 23 #Javascript
详解webpack进阶之loader篇
Aug 23 #Javascript
Vue中定义全局变量与常量的各种方式详解
Aug 23 #Javascript
基于JavaScript实现带数据验证和复选框的表单提交
Aug 23 #Javascript
You might like
推荐一篇入门级的Class文章
2007/03/19 PHP
php5 apache 2.2 webservice 创建与配置(java)
2011/01/27 PHP
php实现递归抓取网页类实例
2015/04/03 PHP
PHP 多进程与信号中断实现多任务常驻内存管理实例方法
2019/10/04 PHP
JQuery动态添加Select的Option元素实现方法
2016/08/29 Javascript
jQuery实现发送验证码并60秒倒计时功能
2016/11/25 Javascript
javascript基于原型链的继承及call和apply函数用法分析
2016/12/15 Javascript
Webpack path与publicPath的区别详解
2018/05/03 Javascript
Vue2.X 通过AJAX动态更新数据
2018/07/17 Javascript
jquery拖拽自动排序插件使用方法详解
2020/07/20 jQuery
vue路由--网站导航功能详解
2019/03/29 Javascript
史上最为详细的javascript继承(推荐)
2019/05/18 Javascript
layui实现下拉框三级联动
2019/07/26 Javascript
vue视频播放暂停代码
2019/11/08 Javascript
vue 实现根据data中的属性值来设置不同的样式
2020/08/04 Javascript
谈谈JavaScript令人迷惑的==与+
2020/08/31 Javascript
JS实现放大镜效果
2020/09/21 Javascript
vue+node 实现视频在线播放的实例代码
2020/10/19 Javascript
vue项目中js-cookie的使用存储token操作
2020/11/13 Javascript
python写的ARP攻击代码实例
2014/06/04 Python
利用python读取YUV文件 转RGB 8bit/10bit通用
2019/12/09 Python
Python学习工具jupyter notebook安装及用法解析
2020/10/23 Python
用canvas实现图片滤镜效果附演示
2013/11/05 HTML / CSS
canvas 阴影和图形变换的示例代码
2018/01/02 HTML / CSS
爱尔兰电脑、家电和家具购物网站:Buy It Direct
2019/07/09 全球购物
旅游管理本科生求职信
2013/10/14 职场文书
电大自我鉴定
2013/10/27 职场文书
应届毕业生的自我鉴定
2013/11/13 职场文书
2014教师教育实践活动对照检查材料思想汇报
2014/09/21 职场文书
董事长岗位职责
2015/02/13 职场文书
2016年全国助残日活动总结
2016/04/01 职场文书
全家福照片寄语怎么写?
2019/04/02 职场文书
电脑只能进入安全模式无法正常启动的解决办法
2022/04/08 数码科技
vue如何清除浏览器历史栈
2022/05/25 Vue.js
纯CSS打字动画的实现示例
2022/08/05 HTML / CSS
ECharts transform数据转换和dataZoom在项目中使用
2022/12/24 Javascript