add an upload file feature to the contact us page

5 years ago
is it possible
to add an attach file  to the contact us page?

and that admin will get this mail with the attachment
2 years ago
Hello,

Is it possible to upload file to the contact us page?


Regards, Lello
2 years ago
Lello wrote:
Hello,

Is it possible to upload file to the contact us page?


Regards, Lello


Yes. possible. See how file uploader works on product details page or cart page. Or you can see admin section too.
2 years ago
Hello Sohel,

Unfortunately, I am not able to do this.
Thanks anyway

Lello
2 years ago
1. Change Nop.Web\Views\Common\ContactUs.cshtml


@model ContactUsModel
@using Nop.Web.Models.Common;
@{
    Layout = "~/Views/Shared/_ColumnsTwo.cshtml";

    //title
    Html.AddTitleParts(T("PageTitle.ContactUs").Text);
}
<div class="page contact-page">
    <div class="page-title">
        <h1>@T("PageTitle.ContactUs")</h1>
    </div>
    @Html.Action("TopicBlock", "Topic", new { systemName = "ContactUs" })
    <div class="page-body">
        @Html.Widget("contactus_top")
        @if (Model.SuccessfullySent)
            {
            <div class="result">
                @Model.Result
            </div>
        }
        else
        {
            using (Html.BeginForm("", "ContactUS", FormMethod.Post, new { enctype = "multipart/form-data" }))
            {
                <div class="message-error">
                    @Html.ValidationSummary(true)
                </div>
                <div class="form-fields">
                    <div class="inputs-left">
                        <div class="inputs">
                            @Html.LabelFor(model => model.Email)
                            <div class="input-box">
                                @Html.TextBoxFor(model => model.Email, new { @class = "email", placeholder = T("ContactUs.Email.Hint") })
                            </div>
                            @Html.ValidationMessageFor(model => model.Email)
                        </div>
                        <br />
                        <div class="inputs">
                            @Html.LabelFor(model => model.FullName)
                            <div class="input-box">
                                @Html.TextBoxFor(model => model.FullName, new { @class = "fullname", placeholder = T("ContactUs.FullName.Hint") })
                            </div>
                            @Html.ValidationMessageFor(model => model.FullName)
                        </div>
                        @if (Model.DisplayCaptcha)
                        {
                            <div class="captcha-box">
                                @Html.Raw(Html.GenerateCaptcha())
                            </div>
                        }
                    </div>
                    <div class="inputs-right inputs">
                        @Html.LabelFor(model => model.Enquiry)
                        <div class="input-box">
                            @Html.TextAreaFor(model => model.Enquiry, new { @class = "enquiry", placeholder = T("ContactUs.Enquiry.Hint") })
                        </div>
                        @Html.ValidationMessageFor(model => model.Enquiry)
                        <br />
                        <br />
                        <div>
                            @Html.Label(T("Common.FileUploader.Upload").Text) <br  />
                            @Html.TextBox("file", "", new { type = "file" }) <br  />
                        </div>

                    </div>
                </div>
                    <div class="buttons">
                        <input type="submit" name="send-email" class="button-1 contact-us-button" value="&nbsp;&nbsp;&nbsp;@T("ContactUs.Button")&nbsp;&nbsp;&nbsp;" />
                    </div>
            }
        }
        @Html.Widget("contactus_bottom")

    </div>
</div>


2. Change Nop.Web\Controllers\CommonController.cs


        [HttpPost, ActionName("ContactUs")]
        [CaptchaValidator]
        public ActionResult ContactUsSend(ContactUsModel model, bool captchaValid, HttpPostedFileBase file)
        {
            //validate CAPTCHA
            if (_captchaSettings.Enabled && _captchaSettings.ShowOnContactUsPage && !captchaValid)
            {
                ModelState.AddModelError("", _localizationService.GetResource("Common.WrongCaptcha"));
            }

            if (ModelState.IsValid)
            {
                string email = model.Email.Trim();
                string fullName = model.FullName;
                string subject = string.Format(_localizationService.GetResource("ContactUs.EmailSubject"), _storeContext.CurrentStore.GetLocalized(x => x.Name));

                var emailAccount = _emailAccountService.GetEmailAccountById(_emailAccountSettings.DefaultEmailAccountId);
                if (emailAccount == null)
                    emailAccount = _emailAccountService.GetAllEmailAccounts().FirstOrDefault();
                if (emailAccount == null)
                    throw new Exception("No email account could be loaded");

                string from;
                string fromName;
                string body = Core.Html.HtmlHelper.FormatText(model.Enquiry, false, true, false, false, false, false);
                //required for some SMTP servers
                if (_commonSettings.UseSystemEmailForContactUsForm)
                {
                    from = emailAccount.Email;
                    fromName = emailAccount.DisplayName;
                    body = string.Format("<strong>From</strong>: {0} - {1}<br /><br />{2}",
                        Server.HtmlEncode(fullName),
                        Server.HtmlEncode(email), body);
                }
                else
                {
                    from = email;
                    fromName = fullName;
                }

                //Attachment
                string _path = "";
                string _FileName = "";
                if (file != null)
                {
                    if (file.ContentLength > 0)
                    {
                        _FileName = Path.GetFileName(file.FileName);
                        _path = Path.Combine(@"d:\inetpub\webs\jurisit\tempDirectory", _FileName);
                        file.SaveAs(_path);
                    }
                }


                _queuedEmailService.InsertQueuedEmail(new QueuedEmail
                {
                    From = from,
                    FromName = fromName,
                    To = emailAccount.Email,
                    ToName = emailAccount.DisplayName,
                    ReplyTo = email,
                    ReplyToName = fullName,
                    Priority = 5,
                    Subject = subject,
                    Body = body,
                    CreatedOnUtc = DateTime.UtcNow,
                    EmailAccountId = emailAccount.Id,
                    AttachmentFileName= _FileName,
                    AttachmentFilePath = _path

                });
                
                model.SuccessfullySent = true;
                model.Result = _localizationService.GetResource("ContactUs.YourEnquiryHasBeenSent");

                //activity log
                _customerActivityService.InsertActivity("PublicStore.ContactUs", _localizationService.GetResource("ActivityLog.PublicStore.ContactUs"));

                return View(model);
            }

            model.DisplayCaptcha = _captchaSettings.Enabled && _captchaSettings.ShowOnContactUsPage;
            return View(model);
        }
2 months ago
Yes, I am aware of this post and it is almost 10 years old and was written for version 3.x of nopCommerce.  I was hoping I can get a more current update of this piece of code that works on version 4.2.
2 months ago
1. Add encryption type (enctype="multipart/form-data") to contact us form.
2. Add file input field inside the form.
3. Get your file in ContactUs action method of CommonController.
var httpPostedFile = Request.Form.Files.FirstOrDefault();
2 months ago
The process of attaching a file to the ContactUs page Form is much more involved than dropping a couple of lines of code into the cshtml and constructor files.  The nopCommerce platform is already sending PDF attachments to users when they make a purchase and this procedure is implemented in the SendMessage constructor function.  I was wondering if I can get some guidance to extend this functionality into the ContactUs form so clients can send me a photo or a file of what they need from my store, in case I do not have it listed on the products catalog.
1 month ago
I coded the constructor and did not get an error during the process, but I am not getting the attachment in the Email that I am receiving.  Debug does display that the attachment is available and I can see the file name in the debug window correctly.  How do I get the attachment to come to my Email?

        public virtual IActionResult ContactUsSend(ContactUsModel model, bool captchaValid, IList<IFormFile> ImageFile)
        {
            //validate CAPTCHA
            if (_captchaSettings.Enabled && _captchaSettings.ShowOnContactUsPage && !captchaValid)
            {
                ModelState.AddModelError("", _localizationService.GetResource("Common.WrongCaptchaMessage"));
            }

            model = _commonModelFactory.PrepareContactUsModel(model, true);

            if (ModelState.IsValid)
            {
                var subject = _commonSettings.SubjectFieldOnContactUsForm ? model.Subject : null;

                MailMessage message = new MailMessage();
                foreach (var file in ImageFile)
                {
                    if (file.Length > 0)
                    {
                        using (var ms = new MemoryStream())
                        {
                            file.CopyTo(ms);
                            var fileBytes = ms.ToArray();
                            Attachment data = new Attachment(new MemoryStream(fileBytes), file.FileName);
                            message.Attachments.Add(data);
                        }
                    }
                }
                          
                message.Body = Core.Html.HtmlHelper.FormatText(model.Enquiry, false, true, false, false, false, false);
                _workflowMessageService.SendContactUsMessage(_workContext.WorkingLanguage.Id,
                    model.Email.Trim(), model.FullName, subject, message.Body);

                model.SuccessfullySent = true;
                model.Result = _localizationService.GetResource("ContactUs.YourEnquiryHasBeenSent");
                message.Dispose();

                //activity log
                _customerActivityService.InsertActivity("PublicStore.ContactUs",
                    _localizationService.GetResource("ActivityLog.PublicStore.ContactUs"));

                return View(model);
            }

            return View(model);
        }
1 month ago
You are calling SendContactUsMessage(...
which in turn calls              
return SendNotification(messageTemplate, emailAccount, languageId, tokens, toEmail, toName,
                    fromEmail: fromEmail,
                    fromName: fromName,
                    subject: subject,
                    replyToEmailAddress: senderEmail,
                    replyToName: senderName);

but it does not pass in the attachment details in the parameters

        public virtual int SendNotification(MessageTemplate messageTemplate,
            EmailAccount emailAccount, int languageId, IEnumerable<Token> tokens,
            string toEmailAddress, string toName,
            string attachmentFilePath = null, string attachmentFileName = null,
            string replyToEmailAddress = null, string replyToName = null,
            string fromEmail = null, string fromName = null, string subject = null)
        {

Is your file being uploaded to the server – can you see it - in what directory ?

You need to provide the attachmentFilePath and attachmentFileName to SendNotification if you are going to use that method