Node. js implements multiple image upload instances

  • 2020-03-30 03:12:17
  • OfStack

First on the renderings:

< img SRC = "border = 0 / / files.jb51.net/file_images/article/201406/201463103948882.jpg? 201453104011 ">

This is the code that I did long pictures at that time, take out for you to use for reference (some places need dear friends to change, the general direction is right)

There are three files involved (in general)

1. Route entry file (I am /routes. Js, many times in /app.js)


  //Add food
  app.all('/add', users.add);

2. Route controller file (I am /routes/users.js)

//Add food
exports.add = function (req, res) {
   if (req.method == "GET") {
        var user = {};
     if(req.session.user){
         user = req.session.user;
     }
    res.render("users/food_add", {title:' Release food -'+config.name,name:config.name,user:user});
  } else  if (req.method == "POST") {
    //To get the data
    var x = req.body.x;
    var y = req.body.y;
    var cat_id = req.body.cat_id;
    var cat_name = req.body.cat_name;
    var address = req.body.address;
    var title = req.body.title;
    var desc = req.body.desc;
    var content = req.body.content;
    var pics = '';
    var price = req.body.price;
    var tags = req.body.tags;
    var add_time = Date.parse(new Date())/1000;
    var support = 0;
    var uid = req.body.uid;
    //Image uploading
    //console.dir(req.files);
    var file_obj = req.files.pics;
    //console.log(file_obj.length);
    var file_obj2 = [];
    for(var i=0;i<file_obj.length;i++){
        if(file_obj[i].name){
            file_obj2.push(file_obj[i]);
        }
    }
    var length = file_obj2.length;
    if(length>0){
        file_obj2.forEach(function(item,index){
            if(item.path){
            var tmpPath = item.path;
            var type = item.type;
            var extension_name = "";
            //Move to the specified directory, usually under public images files
            //Make sure the path already exists while moving, otherwise an error will be reported
            var tmp_name = (Date.parse(new Date())/1000);
            tmp_name = tmp_name+''+(Math.round(Math.random()*9999));
            //Determine file type
            switch (type) {
                case 'image/pjpeg':extension_name = 'jpg';
                    break;
                case 'image/jpeg':extension_name = 'jpg';
                    break;
                case 'image/gif':extension_name = 'gif';
                    break;
                case 'image/png':extension_name = 'png';
                    break;
                case 'image/x-png':extension_name = 'png';
                    break;
                case 'image/bmp':extension_name = 'bmp';
                    break;
            }
            var tmp_name = tmp_name+'.'+extension_name;
            var targetPath = 'public/images/' + tmp_name;
            console.log(tmpPath);
            //Moves the uploaded temporary file to the specified directory
            fs.rename(tmpPath, targetPath , function(err) {
                if(err){
                    throw err;
                }
                if(pics){
                    pics += ','+tmp_name;
                }else{
                    pics += tmp_name;
                }
                //Determine if it's done
                //console.log(index);
                 //Delete temporary file
                fs.unlink(tmpPath, function(){
                    if(err) {
                        throw err;
                    }else{
                        if((index+1)==length){
                    console.log(targetPath);
                    //Upload processing completed
                    // data 
                    var data = {
                        x:x,// longitude 
                        y:y,// The dimension 
                        cat_id:cat_id,//Category id
                        cat_name:cat_name,//Category name
                        address:address,// address 
                        title:title,// The title 
                        desc:desc,// Introduction to the 
                        content:content,// content 
                        pics:pics,//Image field, separated by ','
                        price:price,// The price 
                        tags:tags,//Labels are separated by ','
                        add_time:add_time,//support
                        support:support,//support  The default is 0
                        uid:uid//The user id can be anonymous
                    };
                    food_preDao.insert(data, function (err, food) {
                        if(err){
                            res.json({err:100,content:' Database error '});
                        }else{
                            res.json({err:0,content:' Release successful! ',data:food});
                        }
                    });
                }
                    }
                });

            });
            }
         });
    }else{
        //No picture
        // data 
        var data = {
            x:x,// longitude 
            y:y,// The dimension 
            cat_id:cat_id,//Category id
            cat_name:cat_name,//Category name
            address:address,// address 
            title:title,// The title 
            desc:desc,// Introduction to the 
            content:content,// content 
            pics:pics,//Image field, separated by ','
            price:price,// The price 
            tags:tags,//Labels are separated by ','
            add_time:add_time,//support
            support:support,//support  The default is 0
            uid:uid//The user id can be anonymous
        };
        food_preDao.insert(data, function (err, food) {
            if(err){
                res.json({err:100,content:' Database error '});
            }else{
                res.json({err:0,content:' Release successful! ',data:food});
            }
        });
    }

  }
};

3. View file (I am /views/users/food_add.ejs)

<style>
    .upload_item{ width: 50px; height: 45px; overflow: hidden;border: 2px dashed #bfbfbf; float: left;margin-right: 10px;}
    .upload_item_add{  width: 50px; height: 45px; display: block; line-height: 42px; text-align: center; font-size: 30px; cursor: pointer;}
    .upload_input{ }
</style>
<script>
    var ADD = {
        upload_click:function(obj){
            $(obj).parent().children().eq(1).click();
        },
        upload_change:function(obj){
            var path;
            path=$(obj).val();      //C:Documents and Settingshud desktop  addfile.jpg
            var aa;
            aa=path.split('.');
            //alert(aa[aa.length-1]);  //jpg  The results of 
            var name;
            name=path.split('\'); 
            var bb=name[name.length-1];             
            //alert(bb.substr(0,bb.indexOf('.')));  //AddFile  The results of 
            $(obj).parent().children().eq(0).css('fontSize','12px');
            $(obj).parent().css('borderStyle','solid');
            $(obj).parent().children().eq(0).html(bb.substr(0,bb.indexOf('.')));
            if($(obj).parent().attr('index')==1){// new 
                var html = '<div class="upload_item" index="1"><span class="upload_item_add" onclick="ADD.upload_click(this)">+</span><input type="file" name="pics" id="pics" class="upload_input" onchange="ADD.upload_change(this)" /></div>';
                $('#upload_box').append(html);
                $(obj).parent().attr('index','0');
            }
        }
     };
</script>
<form method="post" action="/add" enctype="multipart/form-data">
    <table>
        <tr>
            <td> Longitude: </td><td><input type="text" name="x" id="x" /></td>
        </tr>
        <tr>
            <td> Dimensions: </td><td><input type="text" name="y" id="y" /></td>
        </tr>
        <tr>
            <td> Classification: </td><td><select name="cat_id"><option value="1"> classification 1</option></select></td>
        </tr>
        <tr>
            <td> Address: </td><td><input type="text" name="address" id="address" /></td>
        </tr>
        <tr>
            <td> Title: </td><td><input type="text" name="title" id="title" /></td>
        </tr>
        <tr>
            <td> Brief introduction: </td><td><input type="text" name="desc" id="desc" /></td>
        </tr>
        <tr>
            <td> Content: </td><td><input type="text" name="content" id="content" /></td>
        </tr>
        <tr>
            <td> Image: </td><td id="upload_box"><div class="upload_item" index="0" style="display:none;"><span class="upload_item_add" onclick="ADD.upload_click(this)">+</span><input type="file" name="pics" id="pics" class="upload_input" onchange="ADD.upload_change(this)" /></div><div class="upload_item" index="1"><span class="upload_item_add" onclick="ADD.upload_click(this)">+</span><input type="file" name="pics" id="pics" class="upload_input" onchange="ADD.upload_change(this)" /></div></td>
        </tr>
        <tr>
            <td> Price: </td><td><input type="text" name="price" id="price" /></td>
        </tr>
        <tr>
            <td> Tags: </td><td><input type="text" name="tags" id="tags" /></td>
        </tr>
        <tr>
            <td colspan="2"><input type="submit" value=" submit " /></td>
        </tr>
    </table>
</form>


 


Related articles: