如何使用 AngleSharp 将输入文件指定为 DOM of <input type='file'>?

How to specify an input file to DOM of <input type='file'> using AngleSharp?

使用AngleSharp,如何指定要填写的文件<input type="file" name="myInputFile">?我读过这个 Whosebug question,但它似乎与我预期的情况不同。我试图在上传我选择的文件时以编程方式填写表格。

每个IHtmlInputElement都有一个Files属性可以用来添加文件。

var input = document.QuerySelector<IHtmlInputElement>("input[type=file][name=myInputFile]");
input?.Files.Add(file);

在前面使用的示例中,file 变量指的是任何 IFile 实例。 AngleSharp 是一个 PCL 没有开箱即用的正确实现,但是,一个简单的可能看起来像:

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);
    }
}

一个更复杂的方法会自动确定 MIME 类型并具有构造函数重载以允许传入(本地)文件路径等。

希望对您有所帮助!