My setup: asp.net mvc web app with a simple email form with fileUpload and send button.
The email is sent correctly and files are attached - but the attachments are empty.
Debugging the controller gives an InputStream.ReadTimeout in the expression var myFiles = model.MyFiles;
(see below controller code).
Model (only parts)
public List<HttpPostedFileBase> MyFiles { get; set; }
public List<EmailAttachments> Attachments { get; set; }
HTML
<form id="data" method="post" enctype="multipart/form-data">
<input id="files" type="file" aria-label="files" multiple="multiple" name="MyFiles">
</form>
<input type="button" class="btn k-button k-primary" id="send" value="Send" />
Javascript
$(function () {
$("#send").click(function () {
var form = $("#data");
var formData = new FormData(form[0]);
var files = form.find("#files")[0].files;
$.each(files, function() {
var file = $(this);
formData.append(file[0].name, file[0]);
});
$.ajax({
type: "POST",
url: url,
data: formData,
contentType: false,
processData: false,
success: function (response) {
alert("Success");
},
error: function (response) {
alert("Error");
}
});
});
Controller
[HttpPost]
public ActionResult SendCompanyEmail(GeneralEmailViewModel model)
{
...
var myFiles = model.MyFiles; // here occurs the ReadTimeout
if (myFiles != null)
{
foreach (var file in myFiles)
{
if (file != null && file.ContentLength > 0)
{
MemoryStream stream = new MemoryStream(file.ContentLength);
stream.Position = 0;
attachements.Add(new EmailAttachments
{
FileName = file.FileName,
ContentType = file.ContentType,
Stream = stream,
});
}
}
}
// ... code for sending the email ...
}
Any suggestions where the cause for the ReadTimeout could be and how to fix it?
The controller code for building the attachments was faulty. I found a working code:
if (myFiles != null)
{
foreach (var file in myFiles)
{
if (file != null && file.ContentLength > 0)
{
//MemoryStream stream = new MemoryStream(file.ContentLength);
//stream.Position = 0;
attachements.Add(new EmailAttachments
{
FileName = file.FileName,
ContentType = file.ContentType,
Stream = file.InputStream
});
}
}
}
The InputStream.ReadTimeout message still can be read out when debugging the controller. Whether this is just a futile message of no consequence I could not figure out.
Anyway, the approach as outlined in my original post with the correction given above works properly for uploading files and converting them to email attachments.