上传节点FS后文件损坏

时间:2018-01-27 02:39:31

标签: javascript node.js html5 electron filereader

您好我正在使用html5文件读取器和节点fs将文件上传到目前为止我能够执行的服务器,但结果文件比原始文件大。 这是我的代码。

var f = document.getElementById('file').files[0],
    r = new FileReader();
console.log(f); //for checking file info
r.onloadend = function(e) {
    var data = e.target.result;
    var fs = require('fs');
    try {
        fs.writeFileSync(f.name, data, 'utf-8');
        console.log('saved sucessfully!');
    } catch (e) {
        alert('Failed to save the file !');
    }
}

r.readAsBinaryString(f);
}

1 个答案:

答案 0 :(得分:0)

让它发挥作用。我不得不将数据转换为ArrayBuffer

这是我的最终工作代码:

    var fs = require('fs');
    var f = document.getElementById('file').files[0],
        r = new FileReader();
    // console.log('srcPath='+f.path);
    // console.log('savPath='+f.name);

    r.onloadend = function(e) {
        var data = e.target.result;
        try {
            fs.writeFileSync('uploads/' + f.name, Buffer.from(new Uint8Array(this.result)));
            console.log('saved sucessfully!');
        } catch (e) {
            alert('Failed to save the file !');
        }
        //send your binary data via $http or $resource or do anything else with it
    }

    r.readAsArrayBuffer(f);
    console.log('binary=' + r);