如何在 strapi 的寄存器 API 中上传图片?

how to upload image in register API in strapi?

默认注册API,我需要上传注册用户的头像API。那我怎么办呢?我正在发送一个 formData 并且它工作正常。我可以在网络中看到 (binary)

我尝试添加图像字段,它在管理面板中工作,但从 API 端我尝试以 filesprofileImage 等键名发送文件。

我没有得到 res 中的错误。我在水库取得了成功。

问题: 当我重新加载管理面板时,我没有获得用户的个人资料图片。

首先,您必须自定义 user-permission

为此,您必须了解这个概念:https://strapi.io/documentation/3.0.0-beta.x/concepts/customization.html

然后您必须找到要更新的函数 - 在您的例子中,是注册函数。

这里是 tada https://github.com/strapi/strapi/blob/master/packages/strapi-plugin-users-permissions/controllers/Auth.js#L383

因此您必须创建 ./extensions/users-permissions/controllers/Auth.js 内容与原始文件相同。

然后你必须添加

const { parseMultipartData, sanitizeEntity } = require('strapi-utils');
const uploadFiles = require('strapi/lib/core-api/utils/upload-files');

在文件顶部。

然后在你的函数中使用这个 const { data, files } = parseMultipartData(ctx); 解析数据和文件。

那么您必须将 ctx.request.body 替换为 data 以确保使用正确的数据。

之后你必须在用户创建行之后添加这个

https://github.com/strapi/strapi/blob/master/packages/strapi-plugin-users-permissions/controllers/Auth.js#L510

if (files) {
      // automatically uploads the files based on the entry and the model
      await uploadFiles(user, files, { model: strapi.plugins['users-permissions'].models.user })
    }

试试这个方法。我在 React 中使用过,对我来说效果很好。

signUpHandler = () => {
    console.log("SignUp data ::: ", this.state);
    let data = {
        username: this.state.signUpForm.username.value,
        phone: this.state.signUpForm.phone.value,
        email: this.state.signUpForm.email.value,
        password: this.state.signUpForm.password.value
    }
    axios.post('http://0.0.0.0:1337/auth/local/register', data)
    .then(res => {
        console.log(res);
        return res.data.user.id;
    })
    .then(refId =>{
        const data = new FormData();
        data.append('files', this.state.selectedFile);
        data.append('refId', refId);            
        data.append('ref', 'user');
        data.append('source', 'users-permissions');
        data.append('field', 'profileImage');
        return axios.post('http://0.0.0.0:1337/upload', data)            
    })
    .then(res =>{
        console.log(res);
        alert("You registered successfully...");
        this.props.history.push('/login');            
    })
    .catch(error =>{
        console.log(error);
    })                
}