axios POST请求strapi图像上传[内部服务器错误]

okxuctiv  于 2023-03-02  发布在  iOS
关注(0)|答案(2)|浏览(174)

我用axios上传一张图片到strapi,但是响应是500错误,但是在Postman中请求是200

*** Postman ***

AXIOS代码

let bodyFormData = new FormData();

      bodyFormData.append('files', this.state.avatar, this.state.avatar.name)
      bodyFormData.append('ref', 'user')
      bodyFormData.append('refId', getId())
      bodyFormData.append('field', 'avatar')
      bodyFormData.append('source', 'users-permmissions')

      axios({
        method: 'post',
        url: `${strapi}/upload`,

        headers: {
          'Content-Type': 'multipart/form-data',
          'Authorization': `Bearer ${withToken()}`,

          },
          data: bodyFormData,
      }).then(res=>console.log(res.data)).catch(err=>{console.log(err.response.data.message)})

这到底是什么问题
这是strapi用户模型的一部分

{
     "avatar": {
      "model": "file",
      "via": "related",
      "plugin": "upload",
      "required": false
    }
}
fslejnso

fslejnso1#

解决办法是把Axios扔进垃圾桶。我为这个问题挣扎了一天,这一天我再也回不来了。在https://github.com/axios/axios/issues/318上有一个很长的、有几年历史的帖子,人们抱怨无法让多部分表单上传与Axios一起工作。
我切换到request-promise模块,并使用以下简单代码在几分钟内使其工作:

const fs = require("fs-extra");
const rp = require('request-promise');
let out = await rp({
    method: 'POST',
    uri: 'http://mystrapihost/upload',
    formData: {
        // Like <input type="text" name="ref">
        'ref': "customer",  // name of the Strapi data type, singular
        'field': "attachments", // a field named "attachments" of type "Media"
        'refId': "838e238949ewhd82e8938299e289e99", // strapi ID of object to attach to
        // Like <input type="file" name="files">
        "files": {  // must be called "files" to be "seen" by Strapi Upload module
            name: "myfile.pdf",
            value: fs.createReadStream("/path/to/myfile.pdf"),
            options: {
                filename: "myfile.pdf",
                contentType: 'application/pdf'
            },
        },
    },
    headers: {Authorization: 'Bearer myjwtgobbledygook123456'}  // put your JWT code here
});
console.log(out);

好好享受吧!!

qv7cva1a

qv7cva1a2#

This is how I fixed it for Strapi v4

const onSubmitHandler = async (e) => {
        e.preventDefault();
        const formData = new FormData();

        formData.append('files', image);
        formData.append('ref', 'api::event.event');
        formData.append('refId', evtId);
        formData.append('field', 'image');

        const res = await fetch(`${API_URL}/api/upload`, {
            method: 'POST',
            body: formData,
        });

        if (res.ok) {
            imageUploaded();
        } else {
            console.log(res);
        }
    };

相关问题