zoukankan      html  css  js  c++  java
  • node实现ajax上传图片

    1.前端页面

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>上传图片</title>
        <script src="js/jquery-3.4.1.min.js"></script>
    </head>
    <body>
        <input type="file" name="userImg" id="inp" accept=".jpg,.png">
        <img src="" alt="">
    </body>
    <script>
        var file = $('#inp')[0]
        file.onchange=function(){
            var formData=new FormData();
            formData.append('file',file.files[0]);
            var src=file.files[0].name,
            formart=src.split(".")[1];                                                  
            if(formart=="jpg"||formart=="png"){
                $.ajax({
                    url: '/upload',
                    type: 'POST',
                    data: formData,
                    cache: false,
                    contentType: false,
                    processData: false,
                    success: function(data){
                        if(data.code>0){
                            var src=data.data;
                            if(formart=="jpg"||formart=="png"){
                                $('img').attr('src','img/'+src)
                            }
                        }
                    }
                })
            }else{
                    alert("文件格式不支持上传")
            }
        }
    </script>
    </html>

    2.node服务端代码

     1 et express=require('express');
     2 let app = new express();
     3 let path=require('path');
     4 app.use(express.static(path.join(__dirname, 'public')));
     5 let multer=require("multer");
     6 
     7 //上传图片
     8 var storage = multer.diskStorage({
     9   destination: function (req, file, cb){
    10     cb(null, './public/img')//图片存放路径
    11   },
    12   filename: function (req, file, cb){
    13     cb(null, file.originalname)
    14   }
    15 });
    16 var upload = multer({
    17   storage: storage
    18 });
    19 app.post('/upload', upload.single('file'), function (req, res, next) {
    20   var url = req.file.originalname;
    21   res.json({
    22     code : 1,
    23     data : url
    24   });
    25   res.end();
    26 });
    27 
    28 
    29 app.listen(8080, () => console.log('服务开启成功'));
  • 相关阅读:
    添加远程库
    Git远程仓库
    Git 删除文件
    Git撤销暂存区stage中的内容
    Git 暂存区的概念
    Git add和commit步骤分析
    2017CCPC秦皇岛 E题String of CCPC&&ZOJ3985【模拟】
    2017CCPC秦皇岛 C题Crusaders Quest&&ZOJ3983【模拟+STL】
    2017CCPC秦皇岛 L题One-Dimensional Maze&&ZOJ3992【模拟】
    HDU2444 The Accomodation of Students【匈牙利算法】
  • 原文地址:https://www.cnblogs.com/pony-Bug/p/13083751.html
Copyright © 2011-2022 走看看