Get file upload for email attachment umbraco - attachment

I am creating one simple page which has one form. Its code is like below :
#inherits Umbraco.Web.Mvc.UmbracoTemplatePage
#using System.Net;
#using System.Net.Mail;
#{
if(IsPost)
{
//Way 1: to get attachment
var fileSavePath = "";
var uploadedFile = Request.Files[0];//Here not getting file name
var fileName = Path.GetFileName(uploadedFile.FileName);
fileSavePath = Server.MapPath("~/media/" + fileName);
uploadedFile.SaveAs(fileSavePath);
FileInfo info = new FileInfo(fileSavePath);
string[] ext = fileName.Split('.');
//Way 2 :
var a = Request["fluld"];//Getting file name only
var b = Request.Files;//Getting null here
string d = Path.GetFullPath(Request["fluld"]);
string c = string.Empty;
try
{
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
mail.From = new MailAddress("xyz#gmail.com");
mail.To.Add("xyz#gmail.com");
mail.Subject = "Test Mail";
mail.Body = "This is for testing SMTP mail from GMAIL";
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment("filepath");
mail.Attachments.Add(attachment);
SmtpServer.Port = 587;
SmtpServer.Credentials = new System.Net.NetworkCredential("xyz#gmail.com", "******");
SmtpServer.EnableSsl = true;
//SmtpServer.Send(mail);
//MessageBox.Show("mail Send");
}
catch (Exception ex)
{
throw new Exception(ex.Message.ToString());
}
}
}
<form method="post">
<input type="file" name="fluld" id="fluld" />
<input type="submit" value="Sub"/>
</form>
I am not able to get file for email attachment with this Request.Files. Help me with this. Any thing I need to add? This code is in template of umbraco.
Thanks
Dipa

Your form needs to be a 'multipart/form-data'
<form enctype="multipart/form-data" method="post">
<input type="file" name="fluld" id="fluld" />
<input type="submit" value="Sub"/>
</form>

Related

How to upload Multiple Files in Blob storage in DotNetCore

I am able to Upload a Single Text File when I am trying to upload multiple Files its only taking Single
File can some one help me how to upload multiple text file:
public DemoController(IConfiguration configuration)
{
_configuration = configuration;
}
My Create Method:
public async Task<IActionResult> Create(IFormFile files)
{
string blobstorageconnection = _configuration.GetValue<string>("blobstorage");
byte[] dataFiles;
CloudStorageAccount cloudStorageAccount = CloudStorageAccount.Parse(blobstorageconnection);
CloudBlobClient cloudBlobClient = cloudStorageAccount.CreateCloudBlobClient();
CloudBlobContainer cloudBlobContainer = cloudBlobClient.GetContainerReference("demodata");
BlobContainerPermissions permissions = new BlobContainerPermissions
{
PublicAccess = BlobContainerPublicAccessType.Blob
};
string systemFileName = files.FileName;
await cloudBlobContainer.SetPermissionsAsync(permissions);
await using (var target = new MemoryStream())
{
files.CopyTo(target);
dataFiles = target.ToArray();
Console.WriteLine("upload files Successfully");
}
CloudBlockBlob cloudBlockBlob = cloudBlobContainer.GetBlockBlobReference(systemFileName);
await cloudBlockBlob.UploadFromByteArrayAsync(dataFiles, 0, dataFiles.Length);
return View();
}
My View:(Create.cs html)
#{
ViewData["Title"] = "Create";
}
<div class="row">
<div class="col-md-6">
<form method="post" enctype="multipart/form-data" asp-controller="Demo" asp-action="Create">
<div class="form-group">
<label> Select File </label>
<input class="form-control" name="files" multiple="multiple" type="file" />
</div>
<div class="form-group">
<input class="btn btn-success" type="submit" value="Submit" id="demo" text="Succcessfully Uploaded" />
</div>
</form>
</div>
Please try something like the following (untested code):
public async Task<IActionResult> Create(List<IFormFile> files)
{
string blobstorageconnection = _configuration.GetValue<string>("blobstorage");
CloudStorageAccount cloudStorageAccount = CloudStorageAccount.Parse(blobstorageconnection);
CloudBlobClient cloudBlobClient = cloudStorageAccount.CreateCloudBlobClient();
CloudBlobContainer cloudBlobContainer = cloudBlobClient.GetContainerReference("demodata");
BlobContainerPermissions permissions = new BlobContainerPermissions
{
PublicAccess = BlobContainerPublicAccessType.Blob
};
await cloudBlobContainer.SetPermissionsAsync(permissions);
foreach (var formFile in files)
{
byte[] data;
string systemFileName = formFile.FileName;
await using (var target = new MemoryStream())
{
formFile.CopyTo(target);
data = target.ToArray();
CloudBlockBlob cloudBlockBlob = cloudBlobContainer.GetBlockBlobReference(systemFileName);
await cloudBlockBlob.UploadFromByteArrayAsync(data, 0, data.Length);
}
}
return View();
}
Essentially the idea is to pass the collection of files and then loop over this collection in your controller action and upload each item individually.

Send a mail in mvc 3

A question regarding send mail in mvc 3.
When I click on btnApply it should send 2 emails to abcd#gmail.com and also send an acknowledgement to (who filled email id in apply form like be 123#gmail.com)
For example:
Email1 : xyz#gamail.com
Email2 : abcd#gmail.com
Email3 : email entered in apply form, e.g 123#gmail.com
when a Email3 click apply send mail from Email1(Sender) to Email2(receiver) & Email3(receiver)
or
when a Email3 click apply send mail from Email2(Sender) to Email2(receiver) & Email3(receiver)
I have form in popup:
#using (Html.BeginForm()){
Your Full Name
<input type="text" value="" id="txtname" name="txtname" required />
Your Email
<input type="email" value="" id="txtemail" name="txtemail" required />
Upload Your Resume
<input name="Upload Saved Replay" id="btnFile" type="file" />
<input type="button" id="btnApply" name="btnApply" value="Apply" />
}
I have a email manager, it only send 1 mail that from xyz#gmail.com to email id that specified in apply form (123#gmail.com )
public class EmailManager
{
private const string EmailFrom = "xyz#gmail.com";
public static void Enquiry( int JobId, string UserName, string Email, string Massage)
{
using (var client = new SmtpClient()) {
using (var message = new MailMessage(EmailFrom, Email)) {
message.Subject = "Successful";
message.Body = "<html><head><meta content=\"text/html; charset=utf-8\" /></head><body><p>Dear " + UserName +
", </p> <p>Thankyou for Registering</p>"
+ "</a></p><div>Best regards,</div><div>Nisha</div></body></html>";
message.IsBodyHtml = true;
client.EnableSsl = true;
client.Send(message);
};
};
}
}
You could use a for loop between two usings.
string[] Emails = { Email,"abcd#gmail.com", "xyz#gmail.com" }
for(var i = 0; i < 3; i++)
{
using (var message = new MailMessage(EmailFrom, Emails[i]))
{
message.Subject = "Successful";
message.Body = "<html><head><meta content=\"text/html; charset=utf-8\" /></head><body><p>Dear " + UserName +
", </p> <p>Thankyou for Registering</p>"
+ "</a></p><div>Best regards,</div><div>Nisha</div></body></html>";
message.IsBodyHtml = true;
client.EnableSsl = true;
client.Send(message);
};
}
Variable Email comes from void Enquiry, others are hard coded

How generate a unique file name at upload files in webserver (MVC)

a have markup
<div>
#using (Html.BeginForm("Upload","Resume", FormMethod.Post, new { enctype = "multipart/form-data" }))
{ #Html.AntiForgeryToken() <fieldset> <legend>Download Resume</legend> <div class="editor-field">
#Html.TextBox("file", "", new { type = "file" }) </div> <div class="editor-field">
<input type="submit" value="Upload" style="width: 120px; height: 25px; font-size: 1.1em; padding:0" />
</div> </fieldset> }
</div>
and Controller:
[HttpPost]
public ActionResult Upload(HttpPostedFileBase file)
{
try
{
if (file.ContentLength > 0) { var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/uploads"), fileName); file.SaveAs(path);
}
ViewBag.Message = "SuccessUpload";
return RedirectToAction("SuccessUpload", "Resume");
} catch
{ ViewBag.Message = "Fail";
return RedirectToAction("Upload"); }
}
How can generate unique file name at upload files, thanks for answers!
// change file name with its extension
var fileName = Guid.NewGuid().ToString() +
System.IO.Path.GetExtension(file.FileName);
var uploadUrl = Server.MapPath("~/uploads");
file.SaveAs(Path.Combine(uploadUrl, fileName));
One of the way is to concate current date.
var fileName = DateTime.Now.ToString("yyyymmddMMss") + System.IO.Path.GetExtension(file.FileName);

dropdownlistfor produce system.nullreferenceException

I'm trying to create a webpage to send text msg to phone. I'm having trouble getting the carrier drop down list right. It always tells me that "an exception of type 'System.NullReferenceException' occurred in App_Web_ucvryg25.dll but was not handled in user code" when I try to run the code.
Here is my view:
#model MVCTesting2.Models.MailModel
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<fieldset>
<legend>
Send Text
</legend>
#using (Html.BeginForm())
{
#Html.ValidationSummary()
<p>Phone number: </p>
<p>#Html.TextBoxFor(m => m.To)</p>
<p>Carriers</p>
<p>#Html.DropDownListFor(m => m.Carrier,
new SelectList(
new List<Object>{
new { value = "#text.att.net" , text = "att" },
new { value = "#cingularme.com" , text = "cingular" },
new { value = "#messaging.nextel.com" , text = "nextel"}
},
"value",
"text",
Model.Carrier))</p>
<p>Subject: </p>
<p>#Html.TextBoxFor(m => m.Subject)</p>
<p>Body: </p>
<p>#Html.TextAreaFor(m => m.Body)</p>
<input type="submit" value="Send" />
}
</fieldset>
Here is my controller:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mail;
using System.Web;
using System.Web.Mvc;
namespace MVCTesting2.Controllers
{
public class SendTextController : Controller
{
//
// GET: /SendText/
public ActionResult Index()
{
return View();
}
[HttpPost]
public ViewResult Index(MVCTesting2.Models.MailModel _objModelMail)
{
if (ModelState.IsValid)
{
string from = "myemail";
string to = _objModelMail.To;
System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();
mail.To.Add(to);
mail.From = new MailAddress(from, _objModelMail.From, System.Text.Encoding.UTF8);
mail.Subject = _objModelMail.Subject;
mail.SubjectEncoding = System.Text.Encoding.UTF8;
mail.Body = _objModelMail.Body;
mail.BodyEncoding = System.Text.Encoding.UTF8;
mail.IsBodyHtml = true;
mail.Priority = MailPriority.High;
SmtpClient client = new SmtpClient();
//Add the Creddentials- use your own email id and password
client.Credentials = new System.Net.NetworkCredential(from, "mypassword");
client.Port = 587; // Gmail works on this port<o:p />
client.Host = "smtp.gmail.com";
client.EnableSsl = true; //Gmail works on Server Secured Layer
client.Send(mail);
return View("Send");
}
else
{
return View();
}
}
}
}
The model is pretty simple with all the variables.
Any idea why this happened?
Thanks in advance!
You are binding the dropdown list with m=>m.carrier why again you are mentioning Model.Carrier. It is not required , remove it.
And use some thing like this:
#Html.DropDownListFor(m => m.Carrier,
new SelectList(
new List<Object>{
new { value = "#text.att.net" , text = "att" },
new { value = "#cingularme.com" , text = "cingular" },
new { value = "#messaging.nextel.com" , text = "nextel"}
},
"value",
"text"));
Hope this helps...
Looks like you're using Model.Carrier as value for the SelectedValue parameter in the DropDownListFor.
Either you remove Model.Carrier or you put a value in it.

Uploading image using json in aps mvc

I have a function for uploading selected files into folder in asp mvc4. The code in view page is
<form id="form1" method="post" enctype="multipart/form-data" action="EmployeeDetails/Upload">
<input type='file' id="imgInp" accept="image/jpeg"/>
<p>
<input type="submit" value="Upload" class="btn"/>
</p>
</form>
And the controller code is
[HttpPost]
public ActionResult Upload(HttpPostedFileBase imgInp)
{
if (imgInp != null && imgInp.ContentLength > 0)
{
// extract only the fielname
var fileName = Path.GetFileName(imgInp.FileName);
// store the file inside ~/App_Data/uploads folder
var path = Path.Combine(Server.MapPath("~/images/Profile"), fileName);
imgInp.SaveAs(path);
}
return view("Index");
}
Instead of this i want to send the image from view to controller as Json. Or is there any other methods to upload image without refreshing the view page..?
You can send form using ajax...
<form id="login-form">
<input type="file" name="photo" id="files" accept="image/*;capture=camera">
<button type="submit" onclick="submitform()">Submit</button>
</form>
jquery
function submitform(){
var postdata = $('#login-form').serialize();
var file = document.getElementById('files').files[0];
var fd = new FormData();
fd.append("files", file);
var xhr = new XMLHttpRequest();
xhr.open("POST", "/Home/Index", false);
xhr.send(fd);
}
controller
[HttpPost]
public JsonResult Index(FormCollection data)
{
if (Request.Files["files"] != null)
{
using (var binaryReader = new BinaryReader(Request.Files["files"].InputStream))
{
var Imagefile = binaryReader.ReadBytes(Request.Files["files"].ContentLength);//your image
}
}
}
uploading file to the server is quite simple. we need is a html form having encoding type set to multipart/form-data and a file input control.
View: NewProduct.cshtml
<form method="post" enctype="multipart/form-data">
<fieldset>
<legend>New Product</legend>
<div>
<label>Product Name:</label>
#Html.TextBoxFor(x => x.ProductName)
</div>
<div>
<label>Product Image:</label>
<input name="photo" id="photo" type="file">
</div>
<div>
#Html.ValidationSummary()
</div>
<input type="submit" value="Save" />
</fieldset>
</form>
The uploaded files are available in HttpFileCollectionBase of Request.Files.
controller:
[HttpPost]
public ActionResult NewProduct()
{
HttpPostedFileBase image = Request.Files["photo"];
if (ModelState.IsValid)
{
if (image != null && image.ContentLength > 0)
{
var fileName = Path.GetFileName(image.FileName);
string subPath = Server.MapPath("ProductLogo");
bool isExists = System.IO.Directory.Exists(subPath);
if (!isExists)
System.IO.Directory.CreateDirectory(subPath);
var path = Path.Combine(subPath+"\\", fileName);
if (System.IO.File.Exists(path))
{
var nfile = DateTime.Now.ToString() + "_" + fileName;
path = Path.Combine(subPath+"\\", nfile);
}
file.SaveAs(path);
return RedirectToAction("List", "Product");
}
else
{
ModelState.AddModelError("", "Please Select an image");
return View();
}
}
else
{
return View();
}
}

Resources