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="" >
</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(‘服务开启成功‘));

 

node实现ajax上传图片

上一篇:css3 object-fit详解


下一篇:JS spread syntax