C#C
C#3y ago
69 replies
xdd

✅ Fetch

hi 🙂 so, i have small problem with sending form with image to server, can someone please explain how to correctly do that? spend like 3 hours and not found anything useful about that 😦

<form id="formq">
    <p>
        <label for="title"  method="post">Title</label>
    </p>
    <input type="text" id="title" name="title" required>
  
    <p>
        <label for="description">description</label>
    </p>
    <input type="description" id="description" name="description" required>
  
    <p>
        <label for="price">price</label>
    </p>
    <input type="price" id="price" name="price" required>
  
    <label for="image">price</label>
    <input type="file" id="image" name="image" required>
    <p>
        <button type="submit">Add product</button>
    </p>
</form>

that is endpoint for request, but have no clue how to send image with,
app.MapPost("/api/addProduct", [Authorize] (ProductM prod, ShopDbContext db) =>
{

    string fileName = Guid.NewGuid().ToString();
    // save file in folder with new name
    // create Product based on data
    // save to db
    return Results.Ok();
});

like, in case of registration i was sending it like -
const response = await fetch("api/register", {
    method: "POST",
    headers: { "Accept": "application/json", "Content-Type": "application/json" },
    body: JSON.stringify({
        name: document.getElementById("name").value,
        email: document.getElementById("email").value,
        password: document.getElementById("password").value
    })
});


but with images its a bit harder, tried with byte array but don't worked
Was this page helpful?