简体   繁体   English

如何从 URL 下载 JSON 文件?

[英]How to download a JSON file from a URL?

I've got a JSON file on AWS s3.我在 AWS s3 上有一个 JSON 文件。 I want to make a flutter button to trigger a download of that file from the URL.我想制作一个颤动按钮来触发从 URL 下载该文件。 I've looked around stack quite a bit and I find ways to download JSON generated data but not from a URL.我环顾了很多堆栈,找到了下载 JSON 生成数据的方法,但不是从 URL 下载。 I did think this one was promising:我确实认为这个很有希望:

Force external download url 强制外部下载 url

But I can't seem to get it working in flutter.但我似乎无法让它在颤动中工作。 Here's what I'm doing to try to use anchor with "download" attribute.这是我尝试使用带有“下载”属性的锚点所做的事情。

First off, my URL looks like this (this is fake though just for the sake of public stack question)首先,我的 URL 看起来像这样(这是假的,尽管只是为了公共堆栈问题)

https://myfirmware.s3.amazonaws.com/proxy/version.json https://myfirmware.s3.amazonaws.com/proxy/version.json

Then I found this answer:然后我找到了这个答案:

Flutter WEB download option Flutter WEB 下载选项

I tried this but it still (in Chrome Version 80.0.3987.149 (Official Build) (64-bit) shows the JSON in the browser rather than allowing me to save as a file directly on first click of the flutter button.我试过了,但它仍然(在 Chrome 版本 80.0.3987.149(官方构建)(64 位)中)在浏览器中显示 JSON,而不是允许我在第一次单击颤动按钮时直接保存为文件。

My flutter code looks like:我的颤振代码如下所示:

                  child: RaisedButton(
                  elevation: 1.0,
                  onPressed: () => 
                     downloadFile("https://myfirmware.s3.amazonaws.com/proxy/version.json"),
                  child: Text("Proxy Config File")),

My import is:我的进口是:

import 'package:universal_html/html.dart' as html;

And that method is:那个方法是:

      void downloadFile(String url){

    html.AnchorElement anchorElement =  new html.AnchorElement();
    anchorElement.href = url;
    anchorElement.download = 'test.json';
    anchorElement.click();

  }

I am not sure how to see how this gets converted when building flutter for the web.我不确定在为 web 构建颤振时如何看到它是如何转换的。 But I was hoping this would look a lot like they mentioned here:但我希望这看起来很像他们在这里提到的:

Force external download url 强制外部下载 url

Which is:这是:

<a href="http://example.com/media.mp3" download="check this out.mp3">Download Your File</a>

You can use flutter_downloader plugin for this use case.您可以在这个用例中使用flutter_downloader插件。 Create a task with the download URL and target directory for storage.使用下载 URL 和目标目录创建任务以进行存储。

final taskId = await FlutterDownloader.enqueue(
  url: downloadUrl,
  savedDir: downloadPath,
);

Make sure to initialize FlutterDownloader before creating a task.确保在创建任务之前初始化 FlutterDownloader。

WidgetsFlutterBinding.ensureInitialized();
await FlutterDownloader.initialize();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM