Search code examples
jqueryajaxasp.net-corehttp-postform-data

How to upload/send files as email attachment from upload via JQuery Ajax POST call to MVC controller?


I noticed modern browsers excluding IE would show a fake path in Jquery object, which is a security protection to avoid server accessing client side physical drive via browser.

I saw some other posts here and there using formData. I do think it will work with file or maybe files only. But I am in a situation which needs to pass some other information like ID and a couple of string values with the file(s) uploaded to the backend.

My original implementation is like:

Ajax call:

var emails = {
                RequestId: requestId, 
                ToEmails: toEmails,  
                CcEmails: ccEmails,  
                FileList: fileList   
            };

$.ajax({
    url: '@Url.Action("SendEmails")',
    type: 'POST',
    data: JSON.stringify(emails),
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (response) {
    }
});

.Net Core MVC controller:

[HttpPost]
public bool SendEmails([FromBody]ToCcEmails emails)
{
}

Complex object type class:

public class ToCcEmails
{
    public int RequestId { get; set; }
    public string ToEmails { get; set; }
    public string CcEmails { get; set; }
    public List<string> FileList { get; set; }
}

What should I change to my ajax code or even the MVC action file to make it works with the formData solution or any other solution properly?

Thank you.


Solution

  • I do think it will work with file or maybe files only. But I am in a situation which needs to pass some other information like ID and a couple of string values with the file(s) uploaded to the backend.

    If you want to post data with files,your model seems do not correct,here is a working demo below:

    Model:

    public class ToCcEmails
    {
        public int RequestId { get; set; }
        public string ToEmails { get; set; }
        public string CcEmails { get; set; }
        public List<IFormFile> FileList { get; set; }
    }
    

    View:

    <form>
        <input type="text" name="RequestId" />
        <input type="text" name="ToEmails" />
        <input type="text" name="CcEmails" />
        <input type="file" multiple name="FileList" />
    </form>
    
    @section Scripts
    {
    <script>
        $("input[name='FileList']").change(function () {
            var data = new FormData();
    
            $("input[name='FileList']").each(function () {
                var ReadyToUpload = $(this)[0].files;
                if (ReadyToUpload.length > 0) {
                    $.each(ReadyToUpload, function (i, file) {
                        data.append("FileList", file);
                    });
                }
            });
    
            $("form input[type='text']").each(function (x, y) {
                data.append($(y).attr("name"), $(y).val());
            });
            $.ajax({
                url: '@Url.Action("SendEmails")',
                type: 'POST',
                data: data,
               // contentType: "application/json; charset=utf-8",
                dataType: "json",
                processData: false,
                contentType: false,
                success: function (response) {
                }
            });
        })
    </script>
    }
    

    Controller:

    [HttpPost]
    public bool SendEmails([FromForm]ToCcEmails emails)
    {
        return true;
    }
    

    Result: enter image description here