Reputation: 3
Scenario: I have a calling client application which will, in the end generate a .pdf that needs to be emailed out. I have created a aspcore mvc application that acts as an email composer. One of the actions takes the email parameters e.g. To, Cc.. etc and pre-populates part or all of the email form for them to review and press send.
Issue: I'm struggling to pass across a file path to be used in the form as attachment. I also don't think that this is the safest way to do it as it could lead to multiple security vulnerabilities.
My attachments prop from my email class:
public List<IFormFile> Attachments { get; set; }
If the calling app hasn't passed an attachment file path across, the user can use the file input box to select one manually. This works fine. However if a file path is sent across, I can't get this to pre-populate the file input box, like I do with the rest of the form.
if (attachment != null)
{
var fileBytes = System.IO.File.ReadAllBytes(attachment);
MemoryStream ms = new MemoryStream();
ms.Write(fileBytes, 0, fileBytes.Length);
var result = new FileStreamResult(ms, "application/pdf");
IFormFile file = new FormFile(result.FileStream, 0, result.FileStream.Length, "filename", "filename.pdf")
{
Headers = new HeaderDictionary(),
ContentType = "application/pdf",
};
attachmentList.Add(file);
}
I then add it to my model to be passed to the view to pre-populate.
Can you suggest a working way to achieve what I need? and or suggest different ways to achieve it.
Thanks!
Upvotes: 0
Views: 72
Reputation: 62060
"I can't get this to pre-populate the file input box"
...you mean in a browser? No, you can't do that, for security reasons. The browser does not have the ability to specify a file on the user's device without user interaction. This is to prevent malicious websites being able to surreptitiously read otherwise-private data from the filesystems of devices. (And to be honest it's impractical anyway - different operating systems have different filesystem structures, and of course not all files exist on all devices, so specifying a path that would always work is basically impossible.)
But anyway I'm not sure your requirement makes much sense either - from what I can tell you've already generated the PDF and sent it to the MVC application. So the MVC application should just store the file on the server, and then associate it with the form when it's finalised and submitted by the user. Even if it was possible, there would be no value in uploading it a second time.
Upvotes: 1