【问题标题】:Image Upload using fs.writeFile() shows corrupt Images使用 fs.writeFile() 上传图像显示损坏的图像
【发布时间】:2017-12-07 22:37:53
【问题描述】:

我在将图像上传到 Meteor 的 /public 文件夹时遇到问题。 Flow 完美无瑕,只是图像损坏了。

X.html

<form class="documentForm" enctype="multipart/form-data">
    <label for="signature">Upload image of Signature</label>
    <input type="file" name="signature" id="signature" required>

    <label for="panCard">Upload image of Pan Card Only.</label>
    <input type="file" name="panCard" id="panCard" required>

    <button class="btn btn-primary" type="submit">Upload</button>
    <button class="btn btn-warning" id="reset">Reset</button>
</form>

X.js

'submit .documentForm': function(event, template){
    event.preventDefault();
    console.log(event.target.signature.files[0]);
    var signatureImage = event.target.signature.files[0];
    var panCardImage = event.target.panCard.files[0];
    Meteor.call('upload', signatureImage, panCardImage, function(error, response){
      if(error){
        Bert.alert("<strong>Error !</strong> Some Problem occured while submitting documents.", 'danger', 'fixed-top' );
      } else if(response){
        Bert.alert("<strong>Success !</strong> Documents uploaded.", 'success', 'fixed-top' );
      }
    });
    return false;
}

Meteor.method();

'upload'(signatureImage, panCardImage){
    const fs = Npm.require('fs');
    var signatureFileName = Meteor.userId() + "_signature.jpg";
    var panCardFileName = Meteor.userId() + "_pancard.jpg";
    var path = process.env['METEOR_SHELL_DIR'] + '/../../../public/img/userdocuments/';
    /*var encoding = {encoding: 'binary'};*/
    fs.writeFile(path + signatureFileName, signatureImage, Meteor.bindEnvironment(function (err) {
        if (err) {
            log.error(err);
        } else {
            log.debug("Signature upload - " + Meteor.userId());
        }
    }));
    fs.writeFile(path + panCardFileName, panCardImage, Meteor.bindEnvironment(function (err) {
        if (err) {
            log.error(err);
        } else {
            log.debug("Pan Card upload - " + Meteor.userId());
        }
    }));
    return true;

},

为什么我的图像损坏了?我应该怎么做才能纠正我的错误?

【问题讨论】:

    标签: javascript node.js meteor ecmascript-6 fs


    【解决方案1】:

    由于多种原因,您不能(或不应该 - 您选择)将文件添加到 /public 文件夹...

    1. 正在开发中的流星将重新启动 - 这可能会导致损坏
    2. /public 在运行时的位置与您的源所在的位置不同。
    3. 部署meteor代码的文件系统在生产系统上很可能是只读的
    4. 在移动平台上,您无法轻松访问在设备上保存文件,并且空间有限

    虽然技术上可以在文件系统上定义一个位置,您的应用可以在其中保存文件,然后对该位置进行符号链接,使其位于 /public 下的某个位置,或者运行另一个快速服务器来提供这些文件,这并不是真正的最佳做法。

    您应该将上传的文件存储在 AWS S3 等服务上,或者将它们存储在 Mongo 数据库中。有几个包可以帮助你实现这一点,我不禁想到 ostrio:files、vsivsi:file-collection 和 jalik:ufs

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-09-25
      • 2010-12-14
      • 2013-09-13
      • 1970-01-01
      • 2018-05-05
      • 1970-01-01
      • 1970-01-01
      • 2016-09-08
      相关资源
      最近更新 更多