使用fs.writeFile()的图像上传显示损坏的图像

时间:2017-07-04 12:38:58

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

将图像上传到Meteor的/公共文件夹时,我遇到了问题。流程完美无瑕,只有图像是腐败的。

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;

},

为什么我的图片已损坏?我该怎么做才能纠正我的错误?

1 个答案:

答案 0 :(得分:0)

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

  1. 在开发中,meteor将重启 - 这可能会导致损坏
  2. / public在运行时的位置与源的位置不同。
  3. 部署了流星代码的文件系统很可能只能在生产系统上读取
  4. 在移动平台上,您无法轻松访问设备上的文件,且空间有限
  5. 虽然技术上可以在文件系统上定义应用程序可以保存文件的位置,然后将此位置符号链接以使其位于/ public下面,或者运行另一个快速服务器以便提供服务这些文件,并不是最佳实践。

    您应该将上传的文件存储在AWS S3等服务上,或将它们存储在Mongo数据库中。有几个软件包可以帮助你实现这一目标,从我的头脑中开始:ostrio:files,vsivsi:file-collection和jalik:ufs

相关问题