node实现图片的上传功能

原创 纤纤郡主 教程 HTML5 78阅读 2018-10-31 16:42:28 举报

目标

图片的上传


npm install multer --save

banner.ejs

<section class="content-header">

  <h1>

    轮播图管理

  </h1>

  <ol class="breadcrumb">

    <li><a href="#"><i class="fa fa-dashboard"></i> Level</a></li>

    <li class="active">Here</li>

  </ol>

</section>

<!-- Main content -->

<section class="content">

  <!-- Your Page Content Here -->

<div class="box">

            <div class="box-header">

                <a href='/addBannerRoute'><button class = "btn btn-xs btn-success">添加轮播图</button></a>

            </div>

            <!-- /.box-header -->

            <div class="box-body no-padding">

                <table class="table table-striped">

                    <tr>

                        <th>#序号</th>

                        <th>图片</th>

                        <th>操作</th>

                    </tr>

                    <tr>

                        <td> 1</td>

                        <td>

                            <img src=""  style = "height: 50px;width: auto"/>

                        </td>

                        <td>

                            <button class="btn btn-xs btn-warning" >编辑</button>

                            <button class="btn btn-xs btn-danger" >删除</button>

                        </td>

                    </tr>

                </table>

            </div>

            <!-- /.box-body -->

        </div>

</section>

定义添加轮播图路由

addBannerRoute: ( req, res, next ) =>{

    res.render('banner_add');

},

注册路由

router.get('/addBannerRoute', banner.addBannerRoute);

添加轮播图

enctype 属性规定在发送到服务器之前应该如何对表单数据进行编码。

默认地,表单数据会编码为 "application/x-www-form-urlencoded"。就是说,在发送到服务器之前,所有字符都会进行编码(空格转换为 "+" 加号,特殊符号转换为 ASCII HEX 值)。

banner_add.ejs

<section class="content">

            <div class="box box-info">

        <div class="box-header with-border">

          <h3 class="box-title">Horizontal Form</h3>

        </div>

        <!-- /.box-header -->

        <!-- form start -->

        <form class="form-horizontal" enctype = "multipart/form-data" method = "post" action = '/addBannerAction'>

          <div class="box-body">

            <div class="form-group">

              <label for="bannerid" class="col-sm-2 control-label">轮播图id</label>

              <div class="col-sm-10">

                <input type="text" class="form-control" name = "bannerid" id="bannerid" placeholder="轮播图id">

              </div>

            </div>

            <div class="form-group">

              <label for="bannerimg" class="col-sm-2 control-label">上传图片</label>

              <div class="col-sm-10">

                <input type="file" class="form-control" name = "bannerimg" id="bannerimg" >

              </div>

            </div>

            <div class="form-group">

              <label for="" class="col-sm-2 control-label">展示图片</label>

              <div class="col-sm-10">

                <img src = " "  style="width:100px;height:auto;"/>

              </div>

            </div>

                            <div class="form-group">

                                <label for="bannerurl" class="col-sm-2 control-label">链接地址</label>

                                <div class="col-sm-10">

                                    <input type="url" class="form-control" name = "bannerurl" id="bannerurl" placeholder="链接地址">

                                </div>

                            </div>

          </div>

          <!-- /.box-body -->

          <div class="box-footer">

                            <div class="form-group">

                                    <label for="castsalt" class="col-sm-2 control-label sr-only">alt</label>

                                    <div class="col-sm-10">

                                        <input type="submit"class="btn btn-info" value = "添加"/>

                                    </div>

                                </div>

          </div>

          <!-- /.box-footer -->

        </form>

      </div>

 </section>

定义路由addBannerAction, 文件会存放在req.file或者req.files中,文本信息放在req.body中

上传完成得到图片信息只有名字(唯一的filename),后缀需要通过req.file.mimetype获取,以/分割去1,通过fs.rename方法改变名字,原路径为"./uploads/" + req.file.filename;改变后为"./uploads/" + req.file.filename + "." + req.file.mimetype.split('/')[1];,使用串行有关联,将路径传递给下一个函数,下一个函数是连接数据库函数,继续传值给第三个函数插入数据库,最终得到结果

addBannerAction: ( req, res, next ) =>{

// console.log( req.file )

// console.log( req.body )

    var bannerimg = req.file.filename + "." + req.file.mimetype.split('/')[1];

    var oldname = "./uploads/" + req.file.filename;

    var newname = "./uploads/" + bannerimg

   async.waterfall( [

       ( cb ) => {

           fs.rename( oldname, newname, ( err, data ) => {

                if ( err ) throw err;

                 cb( null, bannerimg );

            })

       },

       ( bannerimg, cb ) => {

           MongoClient.connect( mongourl, ( err, db ) => {

           if ( err ) throw err;

                console.log("bannerimg----", bannerimg );

                cb( null, bannerimg, db );

           })

       },

       ( bannerimg, db, cb ) => {

           console.log("bannerimg+++++", bannerimg)

           var { bannerid, bannerurl } = req.body;

           var insertObj = {

               bannerimg,

               bannerid,

               bannerurl

           }

           console.log(insertObj)

            db.collection('banner').insert( insertObj, ( err, data ) => {

                if ( err ) throw err;

                cb( null, "ok");

                db.close();

            })

       }

   ], ( err, result ) => {

       if ( err ) throw err;

       if( result == "ok"){

           res.redirect('/banner')

       }

   })

    /**

     *

     { fieldname: 'bannerimg',

originalname: '党员教育培训.jpg',

encoding: '7bit',

mimetype: 'image/jpeg',

destination: 'uploads/',

filename: 'b752dbc2856609d250de6d10577f4292',

path: 'uploads\\b752dbc2856609d250de6d10577f4292',

size: 44683 }

{ banerid: '111', banerurl: '' }

     */

},

注册路由:注意第二个参数为上传文件时必须写的参数

router.post('/addBannerAction', upload.single('bannerimg'), banner.addBannerAction);

渲染列表......

评论 ( 0 )
最新评论
暂无评论

赶紧努力消灭 0 回复