【问题标题】:How do you hand over files to the user?您如何将文件移交给用户?
【发布时间】:2020-11-11 13:27:26
【问题描述】:

在#WASM / #UNO-platform 项目中,如何将文件移交给用户?

在我的例子中,我在本地生成一个 PDF,并且必须下载它或在浏览器中显示它。

有什么线索吗?
问候, 迈克尔

【问题讨论】:

    标签: uno-platform webassembly


    【解决方案1】:

    目前还没有 API 可以直接执行此操作。但是您可以在锚点 (a) HTML 元素上创建一个 data: 网址。

    为此,您需要创建一些 JavaScript。你可以这样做:

    重要提示:以下代码仅适用于最新版本的 Uno.UI。以v3.0.0-dev.949+开头的版本

    <a> 标签创建一个ContentControl

    [HtmlElement("a")]
    public partial class WasmDownload : ContentControl
    {
        public static readonly DependencyProperty MimeTypeProperty = DependencyProperty.Register(
            "MimeType", typeof(string), typeof(WasmDownload), new PropertyMetadata("application/octet-stream", OnChanged));
    
        public string MimeType
        {
            get => (string) GetValue(MimeTypeProperty);
            set => SetValue(MimeTypeProperty, value);
        }
    
        public static readonly DependencyProperty FileNameProperty = DependencyProperty.Register(
            "FileName", typeof(string), typeof(WasmDownload), new PropertyMetadata("filename.bin", OnChanged));
    
        public string FileName
        {
            get => (string) GetValue(FileNameProperty);
            set => SetValue(FileNameProperty, value);
        }
    
        private Memory<byte> _content;
    
        public void SetContent(Memory<byte> content)
        {
            _content = content;
            Update();
        }
    
        private static void OnChanged(DependencyObject dependencyobject, DependencyPropertyChangedEventArgs args)
        {
            if (dependencyobject is WasmDownload wd)
            {
                wd.Update();
            }
        }
    
        private void Update()
        {
            if (_content.Length == 0)
            {
                this.ClearHtmlAttribute("href");
            }
            else
            {
                var base64 = Convert.ToBase64String(_content.ToArray());
                var dataUrl = $"data:{MimeType};base64,{base64}";
                this.SetHtmlAttribute("href", dataUrl);
                this.SetHtmlAttribute("download", FileName);
            }
        }
    }
    

    在您的 XAML 页面中使用它

    <myControls:WasmDownload FileName="test.txt" x:Name="download">
        Click here to download
    </myControls:WasmDownload>
    

    请注意,您可以将任何内容放入控件的内容中,就像任何其他 XAML ContentControl 一样。

    在后面的代码中设置文件内容

    Loaded += (sender, e) =>
    {
        download.MimeType = "text/plain";
    
        var bytes = Encoding.UTF8.GetBytes("this is the content");
        download.SetContent(bytes);
    };
    

    结果

    Uno 的直接支持

    有一个PR #3380 可以为所有平台原生地将此功能添加到 Uno。你也可以等待它而不是做自定义的方式。

    FileSavePicker 的 PR 已合并,该功能现在可在包 Uno.UI 中使用,自版本 3.0.0-dev.1353 起。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-18
      • 2012-09-02
      • 2019-06-21
      • 2022-01-10
      • 2021-09-15
      • 2011-05-17
      • 1970-01-01
      • 2010-10-18
      相关资源
      最近更新 更多