! . . Album Hình . . !

Tìm kiếm Những Gì Bạn Thích !

5 tháng 8, 2019

net core handle file upload from angular

HTML
<button style="margin-bottom:10px;" mat-raised-button color="accent" (click)="fileUpload.click()">
  {{ 'BUYER.UPLOAD_BUTTON' | translate }}
</button>
<input hidden type="file" id="fileToUpload" #fileUpload multiple (change)="handleFileInput($event)"
  accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" />

TS
  handleFileInput(event) {
    swal({
      title: "Are you Sure",
      type: "warning",
      text: "You want to Upload?",
      confirmButtonText: "Yes, upload it!?",
      showCancelButton: true
    }).then(result => {
      if (result.value) {
        this.loaderService.display(true);
        if (event.target.files && event.target.files.length > 0) {
          this.fileToUpload = <Array<File>>event.target.files;
          debugger;
          const fileToUploadForm = new FormData();

          if (this.fileToUpload) {
            Array.from(this.fileToUpload).forEach(e => {
              fileToUploadForm.append("files", e);
            });

            this.service.uploadToDatabase(fileToUploadForm).subscribe(
              data => {
                this.loaderService.display(false);
                swal({
                  title: "File Upload with the result as follows:",
                  type: "success",
                  html:
                    '<table cellspacing="15" cellpadding="6" style="display:block;margin-left:auto;margin-right:auto; width:60%">' +
                    '<tr><td style="background-color:#5ab857"><span style="color:white;">' +
                    data[0] +
                    " SUCCESSFULLY INSERTED</span></td></tr>" +
                    '<tr><td style="background-color:#dcb455"><span style="color:white;">' +
                    data[1] +
                    " DUPLICATE RECORD</span></td></tr>" +
                    '<tr><td style="background-color:#ED1C24"><span style="color:white;">' +
                    data[2] +
                    " ERROR IN INSERTING</span><td></tr></table>",
                  confirmButtonText: "OK"
                }).then(result2 => {
                  if (result2.value) {
                    setTimeout(_ => this.applyFilter(), 0);
                  }
                });
              },
              error => {
                this.loaderService.display(false);
                swal(
                  "Error",
                  "Invalid file Format or System Error!<br/> " + error,
                  "error"
                );
                setTimeout(_ => this.applyFilter(), 0);
              }
            );
          }
        }
      }
    });
  }

CS
public async Task<IActionResult> HandleUpload(List<IFormFile> files)
{
foreach (var formFile in files)
{
var filePath = System.IO.Path.Combine(Directory.GetCurrentDirectory(), "Files_Upload", formFile.FileName);
if (formFile.Length > 0)
{
using (var stream = new FileStream(filePath, FileMode.Create))
{
await formFile.CopyToAsync(stream);
}
}
}
return Ok(new { count = files.Count });         
}

13 tháng 4, 2019

C# send mail with image attachment and embeded inline

private MailMessage makeupDataForSendMail(string htmlBody, MailMessage mail)
        {
            string regexImgSrc = @"]*?src\s*=\s*[""']?([^'"" >]+?)[ '""][^>]*?>";
            MatchCollection matchesImgSrc = Regex.Matches(htmlBody, regexImgSrc, RegexOptions.IgnoreCase | RegexOptions.Singleline);
            foreach (Match m in matchesImgSrc)
            {
                string src_url = m.Groups[1].Value;
                string pathOfFile = System.Web.HttpContext.Current.Server.MapPath(HttpUtility.UrlDecode(src_url));
                var splitPaths = pathOfFile.Split('.');
                string extention_file = splitPaths[splitPaths.Length - 1].ToLower();
                LinkedResource inline = null;
                switch (extention_file)
                {
                    case "gif":
                        {
                            inline = new LinkedResource(pathOfFile, MediaTypeNames.Image.Gif);
                            break;
                        }
                    case "png":
                        {
                            inline = new LinkedResource(pathOfFile, "image/png");
                            break;
                        }
                    default:
                        inline = new LinkedResource(pathOfFile, MediaTypeNames.Image.Jpeg);
                        break;
                }
                inline.ContentId = Guid.NewGuid().ToString();
                htmlBody = htmlBody.Replace(src_url, "cid:" + inline.ContentId);
                AlternateView avHtml = AlternateView.CreateAlternateViewFromString
               (htmlBody, null, MediaTypeNames.Text.Html);
                avHtml.LinkedResources.Add(inline);
                mail.AlternateViews.Add(avHtml);

                Attachment att = new Attachment(pathOfFile);
                att.ContentDisposition.Inline = true;
                mail.Attachments.Add(att);
            }

            return mail;
        }

        public void sendMail(string htmlBody, string toMail)
        {
            SmtpClient client = new SmtpClient();
            client.Port = int.Parse(this.GetValue("SmtpPort", listVariables));
            client.DeliveryMethod = SmtpDeliveryMethod.Network;
            client.UseDefaultCredentials = false;
            client.EnableSsl = true;
            client.Credentials = new System.Net.NetworkCredential("username", "passwrd");
            client.Host = this.GetValue("SmtpServer", listVariables);

            MailMessage mail = new MailMessage();
            mail.From = new MailAddress("frommail");
            mail.To.Add(toMail);
            mail.Subject = "subject title";
            mail.IsBodyHtml = true;
            mail = makeupDataForSendMail(htmlBody, mail);
            client.Send(mail);
        }

Now you can call: sendMail(, "tomail@com" )

Hướng dẫn đăng nhận xét của bạn

  • Nếu muốn đăng nhận xét của mình các bạn click vào "Xem và nhận xét ở đây" dưới mỗi bài đăng, sau đó hộp thoại xuất hiện bạn gõ vào những nhận xét của mình. thế là xong! cảm ơn các bạn đã ghé thăm blog của mình !