MVC将多个图像发送到控制器

时间:2018-08-05 19:09:09

标签: jquery .net ajax asp.net-mvc asp.net-ajax

从视图将两个图像发送到控制器后,我试图从控制器发送电子邮件。

我尝试了很多事情,当我在控制器中调试Post方法时,该对象始终为空值,但是当我记录发送的数据时,JSON对象不为空,并且包含两个图像以及一个第三个字符串值。

我试图构建与此类似的代码,但是没有运气: Example

我的AJAX通话中肯定缺少某些内容。

这是我的表格:

<!--Photo Modal -->
<div id="cameraModal" class="modal fade" role="dialog">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">&times;</button>
                <h4 class="modal-title"><span id="eventTitle">Send Before/After Photos!</span></h4>
            </div>
            <div class="modal-body">

                <form asp-controller="Home" asp-action="SendClientEmail" method="post" id="photoform" role="form">

                    <div class="form-group">
                        <div class="col-sm-12" style="text-align:left;">
                            <label>Photos:</label>
                        </div>
                        <div class="col-sm-12" style="text-align:left;">
                            <label for="beforePhoto" class="custom-file-upload">
                                <i class="fa fa-cloud-upload"></i> Before Photo
                            </label>
                            <label id="beforePhotoLabel"></label>
                            <input id="beforePhoto" name="beforePhoto" type="file" />

                        </div>
                    </div>

                    <div class="form-group">
                        <div class="col-sm-12" style="text-align:left;">

                            <label for="afterPhoto" class="custom-file-upload">
                                <i class="fa fa-cloud-upload"></i> After Photo
                            </label>
                            <label id="afterPhotoLabel"></label>
                            <input id="afterPhoto" name="afterPhoto" type="file" />

                        </div>
                    </div>

                    <div class="form-group">
                        <div class="col-sm-12" style="text-align:left;">
                            <label>Client Address:</label>
                            <select id="clientAddressSelect" class="form-control">
                                <option value="1" class="form-control">One</option>
                                <option value="2" class="form-control">Two</option>
                            </select>
                        </div>
                    </div>

                    <br />
                    <br />
                    <div class="form-group">
                        <div class="col-sm-12" style="text-align:center;">
                            <button type="button" style="background-color: #222222; border-width: 2px; color: #ffffff;" class="btn btn-default" id="submitPhotos">Submit Photos</button>
                        </div>
                    </div>

                </form>

            </div>
            <div class="modal-footer">
            </div>
        </div>
    </div>
</div>

这是我的控制器代码:

public class Photos
{
    public System.Web.HttpPostedFileBase beforePhoto { get; set; }
    public System.Web.HttpPostedFileBase afterPhoto { get; set; }
    public string clientAddressSelect { get; set; }
}

[HttpPost]
public JsonResult SendClientEmail(Photos imagemodel)
{
    string BeforefileName = Path.GetFileNameWithoutExtension(imagemodel.beforePhoto.FileName);

    string AfterfileName = Path.GetFileNameWithoutExtension(imagemodel.afterPhoto.FileName);

    string Bextension = Path.GetExtension(imagemodel.beforePhoto.FileName);
    string Aextension = Path.GetExtension(imagemodel.afterPhoto.FileName);


    BeforefileName = BeforefileName + "-Before-Photo" + Bextension;
    AfterfileName = AfterfileName + "-After-Photo" + Aextension;

    //send email to client
    SmtpClient client = new SmtpClient("*************");
    MailAddress from = new MailAddress("*************", "*************s");
    MailAddress to = new MailAddress("*************", "*************");

    MailMessage mailMessage = new MailMessage(from, to);
    mailMessage.Subject = "subject";
    mailMessage.Body = "message body";



    mailMessage.Attachments.Add(new Attachment(BeforefileName));
    mailMessage.Attachments.Add(new Attachment(AfterfileName));
    client.Send(mailMessage);


    var status = true;

    var genericResult = new { status = status };
    return new JsonResult { Data = genericResult, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}

这是我的AJAX:

        $('body').on('click', '#submitPhotos', function () {


            //Code I was trying that did not work

            //var $file = document.getElementById('beforePhoto');
            //var $file2 = document.getElementById('afterPhoto');
            //var    $formData = new FormData();

            //var before;
            //if ($file.files.length > 0) {
            //    console.log("First over 0");
            //    for (var i = 0; i < $file.files.length; i++) {
            //        $formData.append('file-' + i, $file.files[i]);
            //        before = $file.files[i];
            //    }
            //}
            //var after;
            //if ($file2.files.length > 0) {
            //    console.log("Second over 0");
            //    for (var i = 0; i < $file.files.length; i++) {
            //        $formData.append('file-' + i, $file2.files[i]);
            //        after = $file2.files[i];
            //    }
            //}

            //data = {
            //    beforePhoto: before,
            //    afterPhoto: after,
            //    clientAddressSelect: "77 hahahaha pl NW"
            //}

            //console.log($formData);

            //$.ajax({
            //    url: '/home/SendClientEmail',
            //    type: 'POST',
            //    data: $formData,
            //    dataType: 'json',
            //    contentType: false,
            //    processData: false,
            //    success: function ($data) {

            //    }
            //});
            console.log("submittingform");
            var $form = $('#SendClientEmail');

            var fileInput = document.getElementById('beforePhoto');
            var filename = fileInput.files[0].name

            var fileInput2 = document.getElementById('afterPhoto');
            var filename2 = fileInput2.files[0].name

             data = {
                 beforePhoto: fileInput.files[0],
                 afterPhoto: fileInput2.files[0],
                clientAddressSelect: "77 hahahaha pl NW"
            }

            $form.append(filename, fileInput.files[0]); 
            $form.append(filename2, fileInput2.files[0]); 

            //$('#cameraModal').modal('hide');
            ////$('#processingModal').modal('show');
            console.log(data);

                $.ajax({
                    type: "POST",
                    url: '/home/SendClientEmail',
                    data: data,
                    dataType: 'json',
                    contentType: false,
                    processData: false,
                    error: function (xhr, status, error) {
                        //do something about the error
                    },
                    success: function (response) {
                        //do something with response


                        //$('#processingModal').modal('hide');
                    }
                });

        });

任何帮助或朝着正确的方向前进,将不胜感激!

1 个答案:

答案 0 :(得分:0)

This Post对我有很大帮助,谢谢大家在评论中缩小我的问题范围。

解决方案是添加

的组合
  

'enctype ='multipart / form-data'

到我的表单,并使用Request对象获取照片,如下所示:

globalarray

像这样正确地将数据发送到我的控制器:

.slice().reverse()