Here I'm using WebApi I want an image for sending Email For that I wrote the code as:
var files = HttpContext.Current.Request.Files;
if (files.Count > 0) {
for (int i = 0; i < files.Count; i++) {
HttpPostedFile file = files[i];
mailModel.filename = file.FileName;
mailModel.filecontent = file.InputStream;
}
}
Here How can i Bind mailModel.Filecontent
My Class File as
public class SendMailRequest
{
public string filecontent { get; set; }
public string filename { get; set; }
}
My Mail Sending Code is:
if (mailModel.filename != null) {
string tempPath = WebConfigurationManager.AppSettings["TempFile"];
string filePath = Path.Combine(tempPath, mailModel.filename);
using(System.IO.FileStream reader = System.IO.File.Create(filePath)) {
byte[] buffer = Convert.FromBase64String(mailModel.filecontent);
reader.Write(buffer, 0, buffer.Length);
reader.Dispose();
}
msg.Attachments.Add(new Attachment(filePath));
How can I Bind my File to the FileContent?
I think you probably want to learn about using Streams in .Net? First use Stream not string here:
public class SendMailRequest
{
public Stream FileContent { get; set; }
public string FileName { get; set; }
}
Then, because it's utterly confusing, rename your reader
to writer
.
Then, don't do anything stringy with your Stream, just do:
await mailModel.filecontent.CopyToAsync(writer);
There is a complication here. This code assumes that the original uploaded filestream is still present and working, in memory, at the time that you try to send your email. Whether that is true depends on what happens in between.
Especially, if the Http request processing has finished and a response been returned before the email gets sent, the filecontent stream has probably already gone away. has A safer course is to do the copy straight away in the controller:
file.InputStream.CopyToASync(mailModel.filecontent)
but at this point I have to say, I would rather either (1) copy straight to a file or (2) copy into a MemoryStream. i.e.
mailModel.filecontent= new MemoryStream();
file.InputStream.CopyToASync(mailModel.filecontent)
(If you use MemoryStream, you must calculate what is the largest file you are willing to handle, and make sure bigger files are rejected before you create the memory stream).
Finally, if this populates your file with Base64 instead of the binary, look at the answers to this question: HttpRequest files is empty when posting through HttpClient