$cripts
Uploading Media via Nuxt Form to a Strapi Endpoint
Strapi Media
content-type: members
member schema:
- id ( system generated ID )
- name ( short text )
- avatar ( single media )
Create member controller:
src\api\member\controllers\member.js
const CONTROLLER_PATH_NAME = "api::member.member";
module.exports = createCoreController(CONTROLLER_PATH_NAME, ({ strapi }) => ({
create: async (ctx) => {
let files = ctx.request.files;
let body = ctx.request.body;
let input = {
title: body.name,
};
if (files) {
input["avatar"] = files["avatar"];
}
const member = await strapi.entityService.create(CONTROLLER_PATH_NAME, {
fields: ["name"],
populate: {
avatar: {
fields: ["url", "name"],
},
},
data: input,
files: files,
});
if (!member) return ctx.response.internalServerError();
return {
data: member,
error: null,
};
},
}));
Create Nuxt Form:
Using Nuxt UI <``UInput``/>
, <``UButton``/>
<template>
<div>
<form @submit="submitForm">
<!-- avatar upload drop zone || preview -->
<div v-if="preview">
<NuxtImg :src="preview" />
</div>
<div v-else>
<label for="avatar">
<div>
<UIcon name="i-heroicons-cloud-arrow-up-solid" />
<p>
<span>Click to upload or drag and drop</span>
</p>
</div>
<input
class="hidden"
type="file"
id="avatar"
ref="avatar"
name="avatar"
@change="onFileChange()"
/>
</label>
</div>
<!-- Name -->
<h6>Name</h6>
<UInput v-model="title" name="title" label="title" />
<UButton label="Submit" block @click="submitForm" :loading="submitting" />
</form>
</div>
</template>
<script setup>
const name = ref("");
const avatar = ref(null);
const preview = ref(null);
const submitting = ref(false);
const path = http://localhost:1337/api/ + "members";
var formData = new FormData();
const onFileChange = () => {
preview.value = URL.createObjectURL(avatar.value.files[0]);
formData.append("avatar", avatar.value.files[0], avatar.value.files[0].name);
};
const submitForm = async () => {
formData.append("name", name.value);
submitting.value = true;
await $fetch(path, {
method: "POST",
body: formData,
});
submitting.value = false;
};
</script>
some modifications to styling, variable names, api etc... to match your needs