Using AngleSharp, how do I specify file to fill in <input type="file" name="myInputFile">
? I've read this StackOverflow question, but it seems like different than my intended case. I'm trying to fill a form programmatically while uploading a file of my choice.
Asked
Active
Viewed 547 times
0
1 Answers
1
Every IHtmlInputElement
has a Files
property that can be used to add files.
var input = document.QuerySelector<IHtmlInputElement>("input[type=file][name=myInputFile]");
input?.Files.Add(file);
In the previously used example the file
variable refers to any IFile
instance. AngleSharp is a PCL does not come with a proper implementation out of the box, however, a simple one may look like:
class FileEntry : IFile
{
private readonly String _fileName;
private readonly Stream _content;
private readonly String _type;
private readonly DateTime _modified;
public FileEntry(String fileName, String type, Stream content)
{
_fileName = fileName;
_type = type;
_content = content;
_modified = DateTime.Now;
}
public Stream Body
{
get { return _content; }
}
public Boolean IsClosed
{
get { return _content.CanRead == false; }
}
public DateTime LastModified
{
get { return _modified; }
}
public Int32 Length
{
get
{
return (Int32)_content.Length;
}
}
public String Name
{
get { return _fileName; }
}
public String Type
{
get { return _type; }
}
public void Close()
{
_content.Close();
}
public void Dispose()
{
_content.Dispose();
}
public IBlob Slice(Int32 start = 0, Int32 end = Int32.MaxValue, String contentType = null)
{
var ms = new MemoryStream();
_content.Position = start;
var buffer = new Byte[Math.Max(0, Math.Min(end, _content.Length) - start)];
_content.Read(buffer, 0, buffer.Length);
ms.Write(buffer, 0, buffer.Length);
_content.Position = 0;
return new FileEntry(_fileName, _type, ms);
}
}
A more sophisticated one would auto-determine the MIME type and have constructor overloads to allow passing in (local) file paths etc.
Hope this helps!

Florian Rappl
- 3,041
- 19
- 25
-
It definitely does help. Thanks! – Nik A. Feb 21 '18 at 14:20