您好,欢迎访问一九零五行业门户网

Express实现前端后端通信上传图片之存储数据库(mysql)傻瓜式教程(一)_javascript技巧

在前端这个坑里摸爬滚打已经一年多了,终于下定决心写下自己第一篇博客(虽然内容原创居少,算是个整合内容),开始使用express的原因是因为自己想测试接收下前端上传图片并返回,实现图片上传。后端各位大大们又都比较忙,没办法了,只能自己上了(哎,都是逼出来的)。
此教程适合没有接触过node的web前端开发,快速构建自己的框架,基于express4.x。
首先安装express ,http://www.expressjs.com.cn/starter/installing.html,安装过程中一直回车到底就ok了。
安装完成后,继续安装express的应用骨架,生成默认项目
$ npm install express-generator -g
(-g表示全局安装,下次可以直接使用,不用再次安装)
接着在myapp文件夹下直接运行express,项目目录就直接生成了
然后安装所有依赖包:
$ npm install
启动这个应用(macos 或 linux 平台):
$ debug=myapp npm start
windows 平台使用如下命令:
> set debug=myapp & npm start
看到这个页面时,大家已经完成了基础的项目构建,继续往上添加自己的代码就可以了。(到这部后大家可以把public目录下的文件夹修改为自己喜欢的格式,例如:js,css,只是一个路径而已)
 接下来大家就可以把自己的页面添加到项目里面了,不过express到目前我只发现可以加载jade模板和ejs。大家不用担心还要从新学习jade,这里http://www.html2jade.org/,可以直接用工具把html转化为jade模板,可以让你手中已有的项目直接添加进去,jade模板在express的加载方法:http://www.expressjs.com.cn/guide/using-template-engines.html。其实jade的写法真的很简单,大家看一下api基本就能上手了,学习地址点这里。(项目里已经集成了jade,不用重复安装)
 现在大家打开核心的app.js
这几行定义的是express的路由,大家可以简单了解下路由的作用,http://www.expressjs.com.cn/guide/routing.html,这点非常重要,一定要理解,不是很难,应该能够很快理解。
比如现在你打开http://localhost:3000/users页面,对应user.js里面的代码一看就能理解。(打开这个页面时发生了get请求)
下面咱们先不急着上传图片,先测试下前端发送的post和get请求。
以post请求为例,咱们把layout.jade修改成下面的样子
doctype htmlhtml head title= title link(rel='stylesheet', href='/css/style.css') script(type=text/javascript, src=/js/jquery.js) script(type=text/javascript, src=/js/index.js) body block content
在public/js下新建个index.js,加载jquery(只是为了简写的ajax)有人可能会问为什么会没有public路径,因为express 内置的 express.static 可以方便地托管静态文件,例如图片、css、javascript 文件等,详细内容点这里,对应app.js的内容为 app.use(express.static(path.join(__dirname, 'public')));
只有这样才能读取到文件。
下面开始修改js代码,public/js/index.js内写个最基础的ajax请求就好了,这里发送请求的路径为/,就是往主页发送请求(路由一定要理解,路由一定要理解,路由一定要理解!!)
$(document).ready(function() { $.post('/', {num: '12345678'}, function(data) { console.log(data) });})
然后在routes/index.js里面修改
var express = require('express');var router = express.router();/* get home page. */router.get('/', function(req, res, next) { res.render('index', { title: 'express' });});router.post('/', function(req, res) { res.send(req.body.num);});module.exports = router;
在此监听首页的post请求,req.body.num表示发送过来的数据,大家可以直接打印下req,看看里面包含了什么内容,加深理解(修改完文件后记得重启express)。
这时候在控制台中就可以看到返回的数据了。
现在大家已经可以使用node接收前端发送的请求了(是不是灰长开心!!),下面进行我们的重头戏,上传图片。
因为是测试接口,公司的项目要兼容低版本浏览器,所有plupload.js就上场了(不是我不想用h5的方法)。官网,下载后如图,就够用了。(记得在layout.jade里面加载)
把index.js修改成下面的样子,这是个标准的官网上传事例,不理解的在官网看下api,很好理解(其实看变量名字也都能理解~)
$(document).ready(function() { var uploader = new plupload.uploader({ runtimes: 'html5,flash,silverlight,html4', browse_button: 'pickfiles', // you can pass an id... container: document.getelementbyid('container'), // ... or dom element itself url: '/', flash_swf_url: '../js/moxie.swf', silverlight_xap_url: '../js/moxie.xap', filters: { max_file_size: '10mb', mime_types: [{ title: image files, extensions: jpg,gif,png }, { title: zip files, extensions: zip }] }, init: { postinit: function() { document.getelementbyid('filelist').innerhtml = ''; document.getelementbyid('uploadfiles').onclick = function() { uploader.start(); return false; }; }, filesadded: function(up, files) { plupload.each(files, function(file) { document.getelementbyid('filelist').innerhtml += '' + file.name + ' (' + plupload.formatsize(file.size) + ')
'; }); }, uploadprogress: function(up, file) { document.getelementbyid(file.id).getelementsbytagname('b')[0].innerhtml = '' + file.percent + %; }, error: function(up, err) { document.getelementbyid('console').appendchild(document.createtextnode(\nerror # + err.code + : + err.message)); }, fileuploaded: function(up, file, info) { // called when file has finished uploading $(body).append($(info.response)) }, uploadcomplete: function(up, file) { } } }); uploader.init();})
index.jade修改成下面的样子,主要是添加上传点击的元素,添加了两个按钮而已(不要嫌弃它确实是比较丑--)
extends layoutblock content h1= title p welcome to #{title} #filelist #container a#pickfiles select files a#uploadfiles upload files
这里我们要用到的外部模块是felix geisendörfer开发的node-formidable模块。它对解析上传的文件数据做了很好的抽象。 其实说白了,处理文件上传“就是”处理post数据 —— 但是,麻烦的是在具体的处理细节,所以,这里采用现成的方案更合适点。
安装formidable模块。
npm install formidable
修改routes/index.js
var express = require('express');var router = express.router();var fs = require('fs');var formidable = require(formidable);/* get home page. */router.get('/', function(req, res) { res.render('index', { title: '孟星魂' });});router.post('/', function(req, res) { var form = new formidable.incomingform(); form.uploaddir = ./public/upload/temp/; //改变临时目录 form.parse(req, function(error, fields, files) { for (var key in files) { var file = files[key]; var fname = (new date()).gettime(); switch (file.type) { case image/jpeg: fname = fname + .jpg; break; case image/png: fname = fname + .png; break; default: fname = fname + .png; break; } console.log(file, file.size); var uploaddir = ./public/upload/ + fname; fs.rename(file.path, uploaddir, function(err) { if (err) { res.write(err + \n); res.end(); } //res.write(upload image:
); res.write(); res.end(); }) } });});
module.exports = router;
 此时需要在public下手动新建文件夹upload以及下面的temp文件夹。
先把文件上传到临时文件夹,再通过fs重命名移动到指定的目录即可。
fs.rename即重命名,但是fs.rename不能夸磁盘移动文件,所以我们需要指定上传的临时目录要和最终目录在同一磁盘下。
res.write就是往前端返回的数据,这里我直接返回一个img标签,并添加上传文件的路径,前端只要把标签append到页面中就ok了。
完成前端图片上传功能!!
今天进行到这里,明天进行讲解node连接数据库的操作。
其它类似信息

推荐信息