使用头像创建用户

问题描述 投票:0回答:1

我想在用户注册中添加一个头像,但我不知道如何,请有人可以与我分享一个完整的例子(表单,JS前端和JS后端)。我正在使用带VueJs的SailsJS 1.0(稳定版)。提前致谢 。

sails.js sails-postgresql
1个回答
2
投票

我想到了。观看这些platzi教程:

以下是视频告诉您的操作:

  1. npm i sails-hook-uploads
  2. api/controllers/entrance/signup.jsinputs键上方添加files: ['avatar'],的新键/值 在inputs添加: avatar: { type: 'ref', required: true }
  3. fn的正文中找到var newUserRecord及其上方添加(即使不需要头像,请确保执行此行,否则您将有一个“unconsuemd文件流超时”: const avatarInfo = await sails.uploadOne(inputs.avatar);
  4. 然后在var newUserRecord = await User.create(_.extend({的第一个参数对象中添加: avatarFd: avatarInfo.fd, avatarMime: avatarInfo.type
  5. api/models/User.js中,将这些属性添加到User模型中: avatarFd: { type: 'string', required: false, description: 'will either have "text" or "avatarFd"' }, avatarMime: { type: 'string', required: false, description: 'required if "avatarFd" provided' },
  6. 然后创建一个下载端点,以下是该操作的查找方式: const user = await User.findOne(id); this.res.type(paste.photoMime); const avatarStream = await sails.startDownload(paste.photoFd); return exits.success(avatarStream);
  7. 添加到此路线下载头像端点的路线。
  8. 然后,您可以通过将<img src="">源指向此下载端点来显示此头像。

- - - 附录 - - -

---- signup.js -----

module.exports = {


  friendlyName: 'Signup',


  description: 'Sign up for a new user account.',


  extendedDescription:
`This creates a new user record in the database, signs in the requesting user agent
by modifying its [session](https://sailsjs.com/documentation/concepts/sessions), and
(if emailing with Mailgun is enabled) sends an account verification email.

If a verification email is sent, the new user's account is put in an "unconfirmed" state
until they confirm they are using a legitimate email address (by clicking the link in
the account verification message.)`,


  files: ['avatar'],

  inputs: {

    emailAddress: {
      required: true,
      type: 'string',
      isEmail: true,
      description: 'The email address for the new account, e.g. [email protected].',
      extendedDescription: 'Must be a valid email address.',
    },

    password: {
      required: true,
      type: 'string',
      maxLength: 200,
      example: 'passwordlol',
      description: 'The unencrypted password to use for the new account.'
    },

    fullName:  {
      required: true,
      type: 'string',
      example: 'Frida Kahlo de Rivera',
      description: 'The user\'s full name.',
    },

    avatar: {

    }

  },


  exits: {

    success: {
      description: 'New user account was created successfully.'
    },

    invalid: {
      responseType: 'badRequest',
      description: 'The provided fullName, password and/or email address are invalid.',
      extendedDescription: 'If this request was sent from a graphical user interface, the request '+
      'parameters should have been validated/coerced _before_ they were sent.'
    },

    emailAlreadyInUse: {
      statusCode: 409,
      description: 'The provided email address is already in use.',
    },

  },


  fn: async function (inputs) {

    var newEmailAddress = inputs.emailAddress.toLowerCase();

    // must do this even if inputs.avatar is not required
    const avatarInfo = await sails.uploadOne(inputs.avatar);

    // Build up data for the new user record and save it to the database.
    // (Also use `fetch` to retrieve the new ID so that we can use it below.)
    var newUserRecord = await User.create(_.extend({
      emailAddress: newEmailAddress,
      password: await sails.helpers.passwords.hashPassword(inputs.password),
      fullName: inputs.fullName,
      tosAcceptedByIp: this.req.ip,
      avatarFd: avatarInfo.fd,
      avatarMime: avatarInfo.type
    }, sails.config.custom.verifyEmailAddresses? {
      emailProofToken: await sails.helpers.strings.random('url-friendly'),
      emailProofTokenExpiresAt: Date.now() + sails.config.custom.emailProofTokenTTL,
      emailStatus: 'unconfirmed'
    }:{}))
    .intercept('E_UNIQUE', 'emailAlreadyInUse')
    .intercept({name: 'UsageError'}, 'invalid')
    .fetch();

    // If billing feaures are enabled, save a new customer entry in the Stripe API.
    // Then persist the Stripe customer id in the database.
    if (sails.config.custom.enableBillingFeatures) {
      let stripeCustomerId = await sails.helpers.stripe.saveBillingInfo.with({
        emailAddress: newEmailAddress
      }).timeout(5000).retry();
      await User.updateOne(newUserRecord.id)
      .set({
        stripeCustomerId
      });
    }

    // Store the user's new id in their session.
    this.req.session.userId = newUserRecord.id;

    if (sails.config.custom.verifyEmailAddresses) {
      // Send "confirm account" email
      await sails.helpers.sendTemplateEmail.with({
        to: newEmailAddress,
        subject: 'Please confirm your account',
        template: 'email-verify-account',
        templateData: {
          fullName: inputs.fullName,
          token: newUserRecord.emailProofToken
        }
      });
    } else {
      sails.log.info('Skipping new account email verification... (since `verifyEmailAddresses` is disabled)');
    }

    // add to pubilc group
    const publicGroup = await Group.fetchPublicGroup();
    await Group.addMember(publicGroup.id, newUserRecord.id);


  }

};
© www.soinside.com 2019 - 2024. All rights reserved.