I am building an upload service into my Next.js application where people can upload music.
Everything works to plan until i have to send the file to my .net webapi. The weird thing is that i am sending a valid FormData file with the right headers, still my IFormFile stays null everytime i make a post request to upload.
Next.js component:
import React, { useState } from 'react'
import { useUser } from '@auth0/nextjs-auth0/client'
import { ChevronDownIcon } from '@heroicons/react/24/outline';
import axios from 'axios';
function MyMusic({token}) {
const { user, error, isLoading } = useUser();
const [selectedFile, setSelectedFile] = useState(null);
const handleFileChange = (event) => {
const file = event.target.files[0];
setSelectedFile(file)
console.log(selectedFile);
};
const handleUpload = async (e) => {
e.preventDefault();
const formData = new FormData();
formData.append('audio', selectedFile);
try {
const response = await axios.post('/api/upload/postUpload', formData, {
headers: {
'Content-Type': 'multipart/form-data',
},
});
console.log(response.data);
} catch (error) {
console.error('Error uploading audio file:', error);
}
}
return (
<div className="flex-grow text-white">
<header className="absolute top-5 right-8">
{
(user &&
<div className="flex items-center bg-black space-x-3 opacity-90 hover:opacity-80 cursor-pointer rounded-full p-1 pr-2">
<img className="rounded-full w-10 h-10" src={user.picture} alt=""/>
<h5>{user.name}</h5>
<ChevronDownIcon className="h-5 w-5" />
</div>
)
}
</header>
<section className={"flex items-end space-x-7 bg-gradient-to-b to-black from-purple-500 h-80 text-white padding-8"}>
</section>
<div class="flex flex-col items-center justify-center text-white">
<h1 className='flex font-bold text-2xl pb-5'>Upload your podcast</h1>
<div class="w-full max-w-xs">
<form class="bg-white shadow-md rounded px-8 pt-6 pb-8 mb-4" enctype="multipart/form-data">
<div class="mb-4">
<label class="block text-gray-700 text-sm font-bold mb-2" for="username">
File
</label>
<input class="shadow border rounded w-full py-2 px-3 leading-tight focus:outline-none focus:shadow-outline" type="file" name="file" placeholder="file" onChange={handleFileChange}/>
</div>
<button class="flex items-center space-x-2 bg-purple-500 hover:bg-purple-700 text-white font-bold py-2 px-4 rounded-full" onClick={handleUpload}>
Upload
</button>
</form>
</div>
</div>
</div>
)
}
export default MyMusic
When i make the call to the Next.js server-side api i retrieve the file with Formidable. Then i put the file in a FormData and send it to my webapi.
Server-side api:
import formidable from "formidable";
export const config = {
api: {
bodyParser: false,
}
}
export default async function handler(req, res) {
if (req.method !== 'POST') {
res.status(405).json({ error: 'Method Not Allowed' });
return;
}
const form = new formidable.IncomingForm();
form.parse(req, (err, fields, files) => {
if (err) {
console.error('Error parsing form data:', err);
res.status(500).json({ error: 'Internal Server Error' });
return;
}
// Access the uploaded file
const audioFile = files.audio;
uploadFile(audioFile);
res.status(200).json({ message: 'Message uploaded!' });
});
}
async function uploadFile(audioFile) {
const form = new FormData();
form.append('file', audioFile);
console.log(form);
const response = await fetch('http://localhost:5222/api/Values/upload', {
method: 'POST',
headers: {
"Content-Type": "multipart/form-data"
},
body: form,
});
}
This is the output of the console.log(form):
FormData {
[Symbol(state)]: [
{
name: 'file',
value: 'PersistentFile: 6e3e4777a88ff2649a0040400, Original: nelk_pod_export (1).wav, Path: /var/folders/m7/jxmplnsd7t74s8cy1fxfc1bw0000gn/T/6e3e4777a88ff2649a0040400'
}
]
}
After this my IFormFile in my webapi stays null. I have no idea what i am doing wrong, i asked ChatGPT but no success, i read multiple articles and tutorial but also no success, i hope someone can tell me what i am doing wrong. This shouldn’t be such a pain to accomplish.
If i upload a file through swagger, it works fine.