Как загрузить несколько изображений в приложение Sails.js - PullRequest
1 голос
/ 20 марта 2019

Предыстория

Я создаю онлайн-рынок для подержанных автомобилей, где владельцы могут перечислять свои автомобили на продажу, а покупатели могут легче найти доступные подержанные автомобили.

Я использую 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 action использует стандартные req/res объекты в формате Sails.js actions2.

Вся документация Sails о загрузке файлов указывает на реализацию анализатора тела Sails под названием Skipper , но я чувствую, что документации по новому синтаксису actions2 не хватает.

Может кто-нибудь указать мне конкретный пример реализации этой функции загрузки файлов, особенно для загрузки нескольких файлов изображений?

...