0

I have tried IFormCollection and tried to deserialization of JSON but nothing worked for me. I'm new to ASP.NET Core, React and Axios. I'm working on a feature where user can upload multiple files and can provide details of that event.

I have used following code.

uploadFiles() {
    var eventDate = moment(this.state.dateOfEvent).format("DD/MM/YYYY");
    var eDate = Date.parse(eventDate)
    var formData = new FormData();
    formData.append("Event_name", this.state.eventName);

    var imgArr = [];
    for (var i = 0; i < this.state.chosenImages.length; i++) {
        imgArr.push(this.state.chosenImages[i]);
    }

    var jsonImgs = JSON.stringify(imgArr);
    formData.append("Image_Path", jsonImgs);
    formData.append("Event_Date", eventDate);
    axios({
        method: 'POST',
        url: '/api/Account/UploadGalleryImages',
        contentType: 'application/json',
        data: formData,
    }).then(function (response) {
        if (response.data.status == "SUCCESS") {
            confirmAlert({
                title: 'Gallery',
                message: response.data.message,
                buttons: [
                    {
                        label: 'Okay',
                        onClick: () => window.location.replace('/Reload_Window')
                    },
                ]
            });
        }
        else {
            console.log("Response:", response);
            confirmAlert({
                title: 'Window Title',
                message: response.data.message,
                buttons: [
                    {
                        label: 'Okay',
                    },
                ]
            });
        }
    }.bind(this))

}

React Code

<FormGroup>
<Input
    placeholder="Choose Image of Event"
    type="file"
    accept="image/jpeg,image/x-png"
    multiple="multiple"
    className="form-control"
    onChange={(event) => this.handleChosenImages(event.target.files) }
/>

handleChosenImages(chosenFiles) {
    this.setState({
        chosenImages: chosenFiles
    })
}

Request object for controller in ASP.NET Core

    public class GalleryImagesAddRequest
    {
        private string event_name;
        private string event_date;
        private IList<IFormFile> fileCollection;

        public string Event_name { get => event_name; set => event_name = value; }
        public IList<IFormFile> Image_Path { get => fileCollection; set => fileCollection = value; }
        public string Event_Date { get => event_date; set => event_date = value; }
    }

Controller Code for receiving all data.

        [HttpPost("UploadGalleryImages")]
        [Route("api/[controller]/[action]")]
        public string UploadGalleryImages(GalleryImagesAddRequest request)
        {
            Gallery gallery = new Gallery();
            EventDetail eventDetail = new EventDetail();
            Context db = new Context();
            string message = "";

            try
            {
                DateTime dateTime = DateTime.Parse(request.Event_Date).Date;
                eventDetail.event_name = request.Event_name;
                eventDetail.event_date = dateTime;
                db.EventDetail.Add(eventDetail);
                db.SaveChanges();

                message = "SUCCESS";
            }catch(Exception ex)
            {
                new Logger().write(ex);
                message = "failed";
            }

            return message;
        }

Please anyone tell me where I'm making mistake while trying to receive all images at server side?

1 Answer 1

2

First of all, you don't need to serialize files array, and secondly, in order to bind an array in ASP.NET Core you need to append multiple values with the same key to FormData. So change this part of code

var imgArr = [];
for (var i = 0; i < this.state.chosenImages.length; i++) {
    imgArr.push(this.state.chosenImages[i]);
}

var jsonImgs = JSON.stringify(imgArr);
formData.append("Image_Path", jsonImgs);

to

for (var i = 0; i < this.state.chosenImages.length; i++) {
    formData.append("Image_Path", this.state.chosenImages[i]);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot!!! It worked perfectly. After a long time and so many days, finally my controller received selected files. I wanna give more than one vote to this answer but I can't. Thank you so much @Alexander.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.