2

我正在使用NodeJSMulter将文件上传到S3

从表面上看,一切似乎都在工作,文件被上传,我可以在bucket登录AWS控制台时看到它们。但是,大多数情况下,当我点击文件的链接时,文件已损坏,通常文件大小比原始文件小得多。

当文件到达服务器时,文件大小是正确的log,但在S3上它要小得多。例如,我刚刚上传了一个 151kb 的文件。该post请求正确记录了文件大小,但在S3上,该文件显示为 81kb。

客户端:

uploadFile = (file) ->
    formData = new FormData()
    formData.append 'file', file


    xhr = new XMLHttpRequest()
    xhr.open "POST", "/upload-image", true
    # xhr.setRequestHeader("Content-Type","multipart/form-data");

    console.log 'uploadFile'

    xhr.onerror = ->
        alert 'Error uploading file'
    xhr.onreadystatechange = ->
        if xhr.readyState is 4
            console.log xhr.responseText

    xhr.send formData

服务器:

app.use(multer({ // https://github.com/expressjs/multer
      inMemory: true,
      limits : { fileSize:3000000 },
      rename: function (fieldname, filename) {
        var time = new Date().getTime();
        return filename.replace(/\W+/g, '-').toLowerCase() + '_' + time;
      },
      onFileUploadData: function (file, data, req, res) {
        var params = {
          Bucket: creds.awsBucket,
          Key: file.name,
          Body: data,
          ACL: 'public-read'
        };

        var s3 = new aws.S3();
        s3.putObject(params, function (perr, pres) {
          if (perr) {
            console.log("Error uploading data: ", perr);
          } else {
            console.log("Successfully uploaded data", pres);
          }
        });
      }
    }));

    app.post('/upload-image', function(req, res){
        if (req.files.file === undefined){
            res.end("error, no file chosen");
        } else if (req.files.file.truncated) {
            res.end("file too large");
        } else {
          console.log(req.files.file.size); //logs the correct file size
          var path = creds.awsPath + req.files.file.name;
          res.type('text/plain');
          res.write(path);
          res.end();
        };

    });

编辑:

设置file.bufferbodypermaonFileUploadComplete似乎有效,但我觉得这不是正确的做事方式,以后可能会回来咬我。这种方法可以吗,还是我应该注意这样做的问题?

4

0 回答 0