admin管理员组

文章数量:1123883

I have this class:

public class UploadImageData
{
    public IFormFile Image { get; set; }

    public string ImageUId { get; set; }
    public string Label { get; set; }
    public string Name { get; set; }
}

I have an Imageblock in UI (multiple images in block). Every record has an Image along with Name, Label and ImageUid.

I wanted to pass a list of custom objects (UploadImageData) to an ASP.NET Core Web API, but it is not working as expected. I am passing from fromform.

I'm not getting fileupload for image. Entire block is being passed as a multipart/form-data parameter.

How to pass List<UploadImageData> to an ASP.NET Core Web API?

I tried like this:

 public async Task<IActionResult> UploadImage([FromForm]  List<UploadImageData> uploadImageInput)

I have this class:

public class UploadImageData
{
    public IFormFile Image { get; set; }

    public string ImageUId { get; set; }
    public string Label { get; set; }
    public string Name { get; set; }
}

I have an Imageblock in UI (multiple images in block). Every record has an Image along with Name, Label and ImageUid.

I wanted to pass a list of custom objects (UploadImageData) to an ASP.NET Core Web API, but it is not working as expected. I am passing from fromform.

I'm not getting fileupload for image. Entire block is being passed as a multipart/form-data parameter.

How to pass List<UploadImageData> to an ASP.NET Core Web API?

I tried like this:

 public async Task<IActionResult> UploadImage([FromForm]  List<UploadImageData> uploadImageInput)
Share Improve this question edited yesterday marc_s 754k183 gold badges1.4k silver badges1.5k bronze badges asked yesterday PinkyPinky 714 bronze badges 1
  • Can you share the code on how you are calling the UploadImage API? Or are you using Postman? If yes, share the screenshot how you submit the request to API. – Yong Shun Commented yesterday
Add a comment  | 

1 Answer 1

Reset to default 0

Here is an test html, it works properly.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Test Upload API</title>
</head>
<body>
    <h1>Upload Multiple Images</h1>
    <form id="uploadForm">
        <div id="imageBlocks">
            <div class="image-block">
                <label>Image:</label>
                <input type="file" name="image"><br>
                <label>Image UID:</label>
                <input type="text" name="imageUId" placeholder="Enter Image UID"><br>
                <label>Label:</label>
                <input type="text" name="label" placeholder="Enter Label"><br>
                <label>Name:</label>
                <input type="text" name="name" placeholder="Enter Name"><br>
                <button type="button" onclick="removeBlock(this)">Remove</button>
                <hr>
            </div>
        </div>
        <button type="button" id="addImageBlock">Add Another Image</button><br><br>
        <button type="button" onclick="uploadImages()">Upload</button>
    </form>

    <script>
        document.getElementById('addImageBlock').addEventListener('click', () => {
            const block = document.createElement('div');
            block.className = 'image-block';
            block.innerHTML = `
                <label>Image:</label>
                <input type="file" name="image"><br>
                <label>Image UID:</label>
                <input type="text" name="imageUId" placeholder="Enter Image UID"><br>
                <label>Label:</label>
                <input type="text" name="label" placeholder="Enter Label"><br>
                <label>Name:</label>
                <input type="text" name="name" placeholder="Enter Name"><br>
                <button type="button" onclick="removeBlock(this)">Remove</button>
                <hr>
            `;
            document.getElementById('imageBlocks').appendChild(block);
        });

        function removeBlock(button) {
            button.parentElement.remove();
        }

        async function uploadImages() {
            const form = document.getElementById('uploadForm');
            const formData = new FormData();
            const imageBlocks = document.querySelectorAll('.image-block');

            imageBlocks.forEach((block, index) => {
                const image = block.querySelector('input[name="image"]').files[0];
                const imageUId = block.querySelector('input[name="imageUId"]').value;
                const label = block.querySelector('input[name="label"]').value;
                const name = block.querySelector('input[name="name"]').value;

                if (image) {
                    formData.append(`uploadImageInput[${index}].Image`, image);
                }
                formData.append(`uploadImageInput[${index}].ImageUId`, imageUId);
                formData.append(`uploadImageInput[${index}].Label`, label);
                formData.append(`uploadImageInput[${index}].Name`, name);
            });

            try {
                const response = await fetch('https://localhost:7247/Test/UploadImage', {
                    method: 'POST',
                    body: formData,
                });

                if (response.ok) {
                    const result = await response.json();
                    alert('Upload successful! Response: ' + JSON.stringify(result));
                } else {
                    const error = await response.text();
                    alert('Upload failed! Error: ' + error);
                }
            } catch (err) {
                alert('An error occurred: ' + err.message);
            }
        }
    </script>
</body>
</html>

本文标签: How to pass list of custom object with an image to ASPNET Core Web APIStack Overflow