首页 > 解决方案 > 如何将多个图像上传到 Sails.js 应用程序

问题描述

背景故事

我正在建立一个二手车在线市场,车主可以在其中列出要出售的汽车,买家可以更轻松地找到负担得起的二手车。

我使用Sails.js v1.0 作为我应用程序的 Node.js 框架。

挑战

我希望用户能够将图像添加到他们列出的每辆汽车,Craigslist 风格。

当前实施

这是我到目前为止所拥有的......

images.ejs视图文件中,我有一个ajax-form元素:

<ajax-form class="" action="images" :syncing.sync="syncing" :cloud-error.sync="cloudError" @submitted="submittedForm()" :handle-parsing="handleParsingForm" enctype="multipart/form-data">
          <div class="form-outer flex justify-center items-center h-100 bt bw2">
            <div class="form-inner bg-yellow pa3 w-100">
              <div class="mb3 w-100">
                <label class="db tl mv2 f4" for="upload">Upload</label>
                <input class="pv3" id="upload" type="file"  :class="[formErrors.upload ? 'is-invalid' : '']" v-on:change>
                <div class="bg-light-red light-gray pa2 br2 mt1" v-if="formErrors.upload">Please select at least one image.</div>
              </div>

              <p class="bg-light-red light-gray pa2 br2 mt1" v-if="cloudError"><small>An error occured while processing your request. Please check your information and try again, or <a href="/support">contact support</a> if the error persists.</small></p>
      <div class="">
        <ajax-button :syncing="syncing" class="bg-green pa2 ba b--dark-gray br2 bw1 b circular-bold">Add images.</ajax-button>
      </div>
    </div>
  </div>
</ajax-form>

此表格提交给控制器POST: cars/images.js

module.exports = {


  friendlyName: 'Images',


  description: 'Allow users to upload images of car.',


  inputs: {

  },


  exits: {

  },


  fn: async function (req, res) {

    req.file('upload').upload({
      // don't allow the total upload size to exceed ~10MB
      maxBytes: 10000000
    },function whenDone(err, uploadedFiles) {
      if (err) {
        return res.serverError(err);
      }

      // If no files were uploaded, respond with an error.
      if (uploadedFiles.length === 0){
        return res.badRequest('No file was uploaded');
      }

      // Get the base URL for our deployed application from our custom config
      // (e.g. this might be "http://foobar.example.com:1339" or "https://example.com")
      var baseUrl = sails.config.custom.baseUrl;

      // Save the "fd" and the url where the upload for a user can be accessed
      User.update(req.session.userId, {

        // Generate a unique URL where the upload can be downloaded.
        uploadUrl: require('util').format('%s/user/upload/%s', baseUrl, req.session.userId),

        // Grab the first file and use it's `fd` (file descriptor)
        uploadFd: uploadedFiles[0].fd
      })
      .exec(function (err){
        if (err) return res.serverError(err);
        return res.ok();
      });
    });

  }


};

此控制器/ sails操作req/res使用Sails.js actions2 格式中的标准对象。

所有关于文件上传的 Sails文档都指向名为Skipper的 Sails 正文解析器实现,但我觉得文档缺少新的 actions2 语法。

谁能指出一个实现此文件上传功能的具体示例,尤其是对于上传多个图像文件?

标签: node.jsvue.jsmodel-view-controllersails.js

解决方案


推荐阅读