如何在NodeJs中保存图像

时间:2018-07-27 12:15:38

标签: node.js sockets socket.io

当用户选择图像时,我试图使用NodeJ将它们保存在服务器上。我可以看到该图像已成功保存,但是当我尝试打开该图像时,它没有打开并且文件大小显示为0(零)字节。 我无法找出问题所在。

客户端代码

<input type="file" name="share_file" id="the-file-input" />


$("#the-file-input").change(function() {
    // grab the first image in the FileList object and pass it to the function
    renderImage(this.files[0]);
});

function renderImage(file) {

        // generate a new FileReader object
        var reader = new FileReader();

        // inject an image with the src url
        reader.onload = function(event) {
            the_url = event.target.result;
            socket.binary(true).emit('upload_image', { img: the_url });
        };

        // when the file is read it triggers the onload event above.
        reader.readAsDataURL(file);
    }

socket.on('end_upload', function(data){
    alert('Upload Complete');
});

//服务器端代码

socket.on('upload_image',function(data){
       var nn = 'abcd.jpg';
       data = new Buffer(new Uint8Array(data));
        fs.writeFile('shared_images/'+nn, data, (err) => {
            //delete files[data.name];
            if (err) return socket.emit('upload_error');
            socket.emit('end_upload');
        });
    });

0 个答案:

没有答案
相关问题