I want to create a form that "end user" able to upload file
This file will be sent in email as attachment
I want to know how is it possible,
and if it's not, is it possible to allow "end user" to upload to pre-selected media folder.
This is my try, but there is 2 problem with it:
the file path is not valid because the code runs on server not "end user" machine.
the < input type="file" /> don't return the full file path
-
if (IsPost)
{
//using: string cv = Request["cv"]; don't work
//just return the file name without the path.
var uploadedFile = Request.Files[0];
var fileName = Path.GetFileName(uploadedFile.FileName);
var mailMessage = new MailMessage("emailFrom", "emailTo")
{
Subject = emailSubject,
Body = "some text"
};
var smtpClient = new SmtpClient("mail.123.com", 587)
{
Credentials = new NetworkCredential("username", "password"),
EnableSsl = false
};
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment(fileName );
mailMessage.Attachments.Add(attachment);
smtpClient.Send(mailMessage);
}
You'll need to save the uploaded file to disk first - on the server - using Request.Files[0].SaveAs(pathToFile) (see example here). And then you can get the file path to that to initialise the System.Mail.Attachment class.
Just noting also you'll need an enctype="multipart/form-data" on your <form>.
Suggests no file was uploaded as you say... hence there's nothing at index = 0 (i.e. the first position) in the Request.Files collection. Did you add the enctype="multipart/form-data" attribute to your form?
Allow end user to Upload Files
Hi,
I want to create a form that "end user" able to upload file This file will be sent in email as attachment
I want to know how is it possible,
and if it's not, is it possible to allow "end user" to upload to pre-selected media folder.
This is my try, but there is 2 problem with it:
-
HTML Code:
Thanks in advance!
Hi Tenno
You'll need to save the uploaded file to disk first - on the server - using Request.Files[0].SaveAs(pathToFile) (see example here). And then you can get the file path to that to initialise the System.Mail.Attachment class.
Just noting also you'll need an enctype="multipart/form-data" on your <form>.
Andy
Hi Andy,
Thanks for you reply,
I Got and an exception "Index Out of Range" in this line.
which mean that there is no files uploaded.
BTW, this line executed in the page post back
Do you know why?
Suggests no file was uploaded as you say... hence there's nothing at index = 0 (i.e. the first position) in the Request.Files collection. Did you add the enctype="multipart/form-data" attribute to your form?
I missed that,
Thanks @Andy for your time, it works
I used this Constructor Attachment(Stream, String) to avoid saving file on server
so final code is: -without validation-
Good idea - much better.
is working on a reply...