Загрузить файл с помощью Sails JS и Vue JS - PullRequest
0 голосов
/ 20 октября 2018

Я хочу загрузить файл с помощью Parasails.Но у меня есть ошибка:

<- POST /api/v1/admin/create-article          (3ms 400)
 |  no file attached
 |  No file was attached.
 °

Полагаю, мой синтаксис не очень хорош.Мой HTML-код:

    <div class="form-group">
     <label for="imgFile">Image:</label>
      <input class="form-control-file" id="imgFile"  type="file" :class="[formErrors.imgFile ? 'is-invalid' : '']" autocomplete="imgFile">  
      <div class="invalid-feedback" v-if="formErrors.imgFile">S'il vous plaît, entrez une image valide.</div>
     </div>

Мое действие 2:

module.exports = {
    files: ['imgFile'], 

  friendlyName: 'Create article',

  description: '',

  inputs: {
     imgFile: {
      description: 'Upstream for an incoming file upload.',
      type: 'ref'
     },   
    titre: {
      type: 'string',
      required: true,
    },
    description: {
      type: 'string',
      required: true,
    },
    contenue: {
      type: 'string',
      required: true,
    },

    postDate:{
      type: 'string',
      required: false,
    },

    etiquette:{
      type: 'number',
      required: false,
    },

    sharingLink:{
      type: 'string',
      required: false,
    }
  },


  exits: {
    success: {
      outputDescription: 'The newly created `Thing`.',
      outputExample: {}
    },

    noFileAttached: {
      description: 'No file was attached.',
      responseType: 'badRequest'
    },

    tooBig: {
      description: 'The file is too big.',
      responseType: 'badRequest'
    },
  },


  fn: async function (inputs, exits) {
    var util = require('util');

    // Upload the image.
    var info = await sails.uploadOne(inputs.imgFile, {
      maxBytes: 3000000
    })
    // Note: E_EXCEEDS_UPLOAD_LIMIT is the error code for exceeding
    // `maxBytes` for both skipper-disk and skipper-s3.
    .intercept('E_EXCEEDS_UPLOAD_LIMIT', 'tooBig')
    .intercept((err)=>new Error('The photo upload failed: '+util.inspect(err)));

    if(!info) {
      throw 'noFileAttached';
    }


    var unurl = await sails.helpers.convertUrl(inputs.titre);
    await Article.create({titre:inputs.titre, description:inputs.description, contenue:inputs.contenue ,postDate:inputs.postDate ,sharingLink:inputs.sharingLink,url:unurl, etiquette:inputs.etiquette}).fetch();
    return exits.success();



  }
};

Мой корень:

  'POST /api/v1/admin/create-article':                    { action: 'admin/create-article' },

Я добавил этот пакет в мой проект: sails-hook-uploads

Я новичок в Sails и не понимаю этой ошибки.Спасибо! Как загрузить файл, используя новый формат действий контроллера в sails.js

Ответы [ 2 ]

0 голосов
/ 22 октября 2018
module.exports = {


  friendlyName: 'Update profile avatar',


  description: '',


  inputs: {

  },


  exits: {

    success: {
      responseType: 'redirect'
    },

    failure: {
      responseType: 'redirect'
    },

    unhandleError: {
      responseType: 'redirect',
    }

  },


  fn: async function (inputs, exits) {

    let req = this.req;
    let res = this.res;

    req.file('avatar').upload({
        saveAs: fileName,
        dirname: require('path').resolve(sails.config.appPath, 
                'assets/uploads')
    }, function whenDone(err, uploadedFile) { 
        // your code here
    });
  }


};

Это мой код в контроллере при использовании функции req.file ('имя-файла'). Upload ().Нет необходимости определять файл во входных данных, потому что с помощью req

0 голосов
/ 21 октября 2018

Спасибо за ваши ответы!

Я думаю, что это проблема внешнего интерфейса.Когда я делаю "console.log" на "входах" в моем действии:

{ imgFile: 
   Upstream {
     _fatalErrors: [],
     isNoop: true,
     _files: [],
     timeouts: { untilFirstFileTimer: [Object], untilMaxBufferTimer: [Object] },
     _readableState: 
      ReadableState {
        objectMode: true,
        highWaterMark: 16,
        buffer: [Object],
        length: 0,
        pipes: null,
        pipesCount: 0,
        flowing: null,
        ended: false,
        endEmitted: false,
        reading: false,
        sync: true,
        needReadable: false,
        emittedReadable: false,
        readableListening: false,
        resumeScheduled: false,
        destroyed: false,
        defaultEncoding: 'utf8',
        awaitDrain: 0,
        readingMore: false,
        decoder: null,
        encoding: null },
     readable: true,
     domain: null,
     _events: { error: [Function] },
     _eventsCount: 1,
     _maxListeners: undefined,
     fieldName: 'NOOP_imgFile' },
  titre: 'inputs inputs inputs inputs',
  description: 'inputs inputs inputs',
  contenue: 'inputs inputs inputs',
  postDate: '2019-12-21T09:13',
  etiquette: 1 }

В инструменте Chrome dev:

ответ инструмента

Я думаю, что запрос веб-сокета не является XMLHttpRequest (тип; xhr).

...