Hello. Need assistance with javascript fetch post. I have an api endpoint on backend that receives a file in body. But i can't seem to be able to send it from frontend:
"Required parameter "IFormFile file" was not provided from form."
Here's how i'm trying to send it:
var data = new FormData()
data.append('file', file)
fetch(address, {body: data, method: 'POST'})
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Here are a few things to check and a minimal working example so you can see exactly how the browser marshals your FormData into a multipart/form-data request—and how your ASP-NET Core controller needs to be decorated to pick it up.
1. Front-end: building + sending the FormData
js
// Suppose `fileInput` is <input type="file" /> or you already
// have a JS File object (e.g. from a drag-drop handler).
const file = document.querySelector('#fileInput').files[0];
const formData = new FormData();
formData.append('file', file); // the name "file" must match your C# parameter
fetch('/api/upload', {
method: 'POST',
// IMPORTANT: do *not* manually set the Content-Type header!
// The browser will add: "Content-Type: multipart/form-data; boundary=----..."
body: formData
})
.then(res => {
if (!res.ok) throw new Error(`Server returned ${res.status}`);
return res.json();
})
.then(json => console.log('upload success', json))
.catch(err => console.error('upload error', err));
What to look for in DevTools ➔ Network ➔ Request Payload
You should see something like:
If it’s not showing up as multipart/form-data, you probably overrode the header or your file is undefined.
2. Back-end: your ASP-NET Core controller
By default an IFormFile parameter is not bound from JSON or plain body. You need to tell ASP-NET Core to grab it from the form-data:
csharp
[ApiController]
[Route("api/[controller]")]
public class UploadController : ControllerBase
{
[HttpPost]
// <-- Crucial: [FromForm] tells ASP.NET to look in multipart form-data
public async Task<IActionResult> Post([FromForm] IFormFile file)
{
if (file == null || file.Length == 0)
return BadRequest("No file was uploaded.");
// e.g. save to disk
var path = Path.Combine(_env.ContentRootPath, "uploads", file.FileName);
using var stream = System.IO.File.Create(path);
await file.CopyToAsync(stream);
return Ok(new { fileName = file.FileName, size = file.Length });
}
}
Key points:
[FromForm] — without it, ASP-NET Core won’t pull your file out of the multipart body.
The name you use in formData.append('file', …) must match the parameter name file.
3. Common pitfalls
Manually setting Content-Type on fetch
→ never do that with FormData; it prevents the browser from writing the correct boundary string.
Parameter name mismatch
→ if you append formData.append('avatar', …) but your action is Post(IFormFile file), it won’t bind. They must match or use [FromForm(Name = "avatar")].
File object is empty/undefined
→ make sure you really have a JS File (and not a string path!).
CORS / credentials
→ if your API is on another origin and requires cookies or auth headers, you may need:
With those pieces in place your upload should work end-to-end. Let me know if you’re still seeing problems (or what the network tab shows) and we can drill into it! 😊
User
The file parameter seems to be a string with fakepath instead of some Blob object
Assistant
It turned out that when you read the .value of an <input type="file">, you only get a fake path string (e.g. C:\fakepath\…)—not the actual file. In order to get a real File/Blob you need to pull it off the input’s .files[] collection. Here’s how:
html
<input type="file" id="fileInput" />
<button id="upload">Upload</button>
<script>
document
.getElementById("upload")
.addEventListener("click", () => {
// BAD: this is just a string like "C:\fakepath\foo.png"
// const filePath = document.getElementById("fileInput").value;
// GOOD: this is a real File object
const fileInput = document.getElementById("fileInput");
const file = fileInput.files[0];
if (!file) {
return console.error("No file was selected!");
}
console.log(file instanceof File); // true
console.log(file.name, file.size, file.type);
const formData = new FormData();
formData.append("file", file);
fetch("/api/upload", {
method: "POST",
body: formData,
// NOTE: don't set Content-Type manually!
})
.then(res => res.ok ? res.json() : Promise.reject(res.status))
.then(json => console.log("Uploaded:", json))
.catch(err => console.error("Upload failed:", err));
});
</script>
Key takeaways:
Use input.files[0] (or event.dataTransfer.files[0] if you’re drag-and-dropping) to get a real File object.
Don’t use the .value—that only ever returns a dummy path.
Always let the browser auto-set the Content-Type: multipart/form-data; boundary=… header.
Once you’re sending the actual File the ASP.NET Core endpoint with
csharp
public async Task<IActionResult> Post([FromForm] IFormFile file) { … }