req.file()无法获取多个文件

时间:2018-11-16 07:30:46

标签: html sails.js

我的html代码是

<form action="/file_upload" method="POST" enctype="multipart/form-data">
      <input type="file" name="photos" id="photos" accept='image/*' multiple>
      <input type="submit" value="Upload" id="upload_my_photos" disabled>
</form>

我正在使用帆

uploadFiles = req.file("photos");  

这仅获取单个文件。

编辑:我也想保存单个文件。以下是我正在使用的代码,但没有文件上传:

  req.file('photos').upload(function (err, uploadedPhotos) {
      if (err) return res.serverError(err);
      async.eachSeries(uploadedPhotos, 
        function (uploadedFile, callback) {
          sails.log("upload file size and name is " + uploadedFile.size + " " + uploadedFile.filename);

          req.file(uploadedFile).upload({
            dirname: "path/to/directory",
            // saveAs: function (file, cb) { cb(null, file.filename); }
          },
          function onUploadComplete(err, files) {
              if (err) return res.serverError(err);

              if (files.length === 0) {
                return res.badRequest('No file was uploaded');
              }
              sails.log("files uploaded");
          });
        }, function (err) {
          // if any of the saves produced an error, err would equal that error
          if (err) {
            console.log(err);
          } else {
            return res.status(200).send({ success: false, message: "failed to upload" });
          }
        });
    });

1 个答案:

答案 0 :(得分:1)

风帆req.file()代表从指定字段上传的传入多部分文件。

您需要通过回调订阅请求,在该回调中,上传的文件将作为第二个参数传递:

req.file('photos').upload(function (err, uploadedPhotos){
  if (err) return res.serverError(err);
  return res.json({
    message: uploadedPhotos.length + ' file(s) uploaded successfully!',
    files: uploadedPhotos
  });
});