strapi cms 上传图片

strapi cms 创建实体

Next.js | Strapi Documentation
Integrate Strapi with Next.js.

当有图片时:

数据格式:

files.fieldname (二进制)

data: {}

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>


    <form>
        <!-- Can be multiple files if you setup "collection" instead of "model" -->
        <!-- <input type="text" name="name" /> -->
        <input type="file" name="picture" />
        <input type="submit" value="Submit" />
    </form>

    <script type="text/javascript">
        const form = document.querySelector('form');

        form.addEventListener('submit', async (e) => {
            e.preventDefault();

            const data = {};
            const formData = new FormData();

            Array.from(form.elements)
                .forEach(({ name, type, value, files, ...element }) => {
                    if (!['submit', 'file'].includes(type)) {
                        data[name] = value;
                    } else if (type === 'file') {
                        console.log('files', files)
                        Array.from(files).forEach((file) => {
                            formData.append(`files.${name}`, file, file.name);
                        });
                    }
                });

            formData.append('data', JSON.stringify(data));

            await fetch('http://localhost:1337/api/galleries', {
                method: 'post',
                body: formData,
                headers: {
                    Authorization: "Bearer xxxx"
                },
            });
        });
    </script>
</body>

</html
    >