ajax+node实现图片上传

利用formData实现ajax上传图片后,保存图片到指定收藏夹,然后展示新重命名后的图片

 

html:

 

<input type="file" id="uploadImg" onchange="uploadfile1()"> 

 

 

javascript:

 <script>
            function uploadfile1() {
                console.log('changed')
                var form = new FormData();
                // // form.append('user', document.getElementById('user').value);
    
                var fileobj = document.getElementById('uploadImg').files[0];
                console.log(fileobj)
                form.append('img', fileobj);
                console.log(form)
                var xhr = new XMLHttpRequest();
                xhr.onreadystatechange = function () {
                    if(xhr.readyState === 4 && xhr.status === 200){
                        var data = JSON.parse(xhr.responseText);
                        if (data.status === 200) {
                            console.log(data)
                            var img = document.createElement('img');
                            img.setAttribute('src', data.img);
                            img.setAttribute('class', 'upload-img');
                            console.log(img)
                            document.body.appendChild(img)
                        }
                    }
                };
                xhr.open('POST', 'http://localhost:8080/upload', true);
                xhr.send(form);
            }
        </script>

 

node:

var http = require('http');
var fs = require('fs');
var multiparty = require('./node_modules/multiparty');
var server = http.createServer(function (requset, response){
    var form = new multiparty.Form();

  
    form.parse(requset, function (err, filelds, files) {
        console.log(files)
        fs.renameSync(files.img[0].path, __dirname + '/img/upload.jpeg');
    });
  
    response.setHeader("Access-Control-Allow-Origin", "*"); 
    
    let data = {
        status: 200,
        img: './img/upload.jpeg'
    };
 
    response.end(JSON.stringify(data));
});

server.listen(8080);
console.log('server is running at http://127.0.0.1:8080/');

 

posted @ 2019-12-24 19:00  卡迪斯上小学  阅读(332)  评论(0编辑  收藏  举报