本文将会用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"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:表示加载图片成功后相关信息,打印出来如下:
rejected:表示加载图片失败后,相关信息:
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') )
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
《魔兽世界》大逃杀!60人新游玩模式《强袭风暴》3月21日上线
暴雪近日发布了《魔兽世界》10.2.6 更新内容,新游玩模式《强袭风暴》即将于3月21 日在亚服上线,届时玩家将前往阿拉希高地展开一场 60 人大逃杀对战。
艾泽拉斯的冒险者已经征服了艾泽拉斯的大地及遥远的彼岸。他们在对抗世界上最致命的敌人时展现出过人的手腕,并且成功阻止终结宇宙等级的威胁。当他们在为即将于《魔兽世界》资料片《地心之战》中来袭的萨拉塔斯势力做战斗准备时,他们还需要在熟悉的阿拉希高地面对一个全新的敌人──那就是彼此。在《巨龙崛起》10.2.6 更新的《强袭风暴》中,玩家将会进入一个全新的海盗主题大逃杀式限时活动,其中包含极高的风险和史诗级的奖励。
《强袭风暴》不是普通的战场,作为一个独立于主游戏之外的活动,玩家可以用大逃杀的风格来体验《魔兽世界》,不分职业、不分装备(除了你在赛局中捡到的),光是技巧和战略的强弱之分就能决定出谁才是能坚持到最后的赢家。本次活动将会开放单人和双人模式,玩家在加入海盗主题的预赛大厅区域前,可以从强袭风暴角色画面新增好友。游玩游戏将可以累计名望轨迹,《巨龙崛起》和《魔兽世界:巫妖王之怒 经典版》的玩家都可以获得奖励。
更新日志
- 【雨果唱片】中国管弦乐《鹿回头》WAV
- APM亚流新世代《一起冒险》[FLAC/分轨][106.77MB]
- 崔健《飞狗》律冻文化[WAV+CUE][1.1G]
- 罗志祥《舞状元 (Explicit)》[320K/MP3][66.77MB]
- 尤雅.1997-幽雅精粹2CD【南方】【WAV+CUE】
- 张惠妹.2007-STAR(引进版)【EMI百代】【WAV+CUE】
- 群星.2008-LOVE情歌集VOL.8【正东】【WAV+CUE】
- 罗志祥《舞状元 (Explicit)》[FLAC/分轨][360.76MB]
- Tank《我不伟大,至少我能改变我。》[320K/MP3][160.41MB]
- Tank《我不伟大,至少我能改变我。》[FLAC/分轨][236.89MB]
- CD圣经推荐-夏韶声《谙2》SACD-ISO
- 钟镇涛-《百分百钟镇涛》首批限量版SACD-ISO
- 群星《继续微笑致敬许冠杰》[低速原抓WAV+CUE]
- 潘秀琼.2003-国语难忘金曲珍藏集【皇星全音】【WAV+CUE】
- 林东松.1997-2039玫瑰事件【宝丽金】【WAV+CUE】