【问题标题】:How to download a json file from Primeface app using GSON?如何使用 GSON 从 Primeface 应用程序下载 json 文件?
【发布时间】:2018-07-19 08:20:08
【问题描述】:

我需要从我的应用程序中下载一个文件.json,但要选择它的位置。

  • 我知道如何将文件下载到磁盘,例如图像<p:fileDownload value=""/>

    public StreamedContent getFile(){
        return new DefaultStreamedContent(stream, "image/jpg", "img.jpg"); 
    }
    
  • 我知道如何使用GSON 使用给定路径写入文件

    try(JsonWrite j = new JsonWriter(new OutputStreamWriter(
                              new FileOutputStream("C:\\...\\...\\file.json"), "UTF-8"))){
       j.beginObject();
       // ...
       j.name("foo");
       gson.toJson(myObj, Foo.class, j);
       //...
       j.endObject();
    }catch(...){...}
    

但我不知道如何将两者结合起来才能选择位置并在该位置写入 json?

【问题讨论】:

    标签: java json primefaces download gson


    【解决方案1】:

    所以我不认为你可以做你想做的事。您所能做的就是流式传输您的 JSON 文件并为其命名,例如“test.json”。出于安全原因,您不能告诉浏览器您希望用户下载的位置。我相信它类似于这个请求:Browsing file system to select directory in JSF

    但是,如果您只想发送 GSON 文件以允许用户下载。

    XHTML:

    <p:fileDownload value="#{myController.downloadFile()}" />
    

    JAVA:

    public StreamedContent downloadFile() {
          // convert GSON object to InputStream
          String gson= json.getJSONObject("data").toString();
          InputStream stream = new ByteArrayInputStream(gson.getBytes());
    
          DefaultStreamedContent  content = new DefaultStreamedContent(stream,
                      MediaType.APPLICATION_JSON,
                      "test.json");
    
          return content;
       }
    

    【讨论】:

    猜你喜欢
    • 2011-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-29
    • 1970-01-01
    • 1970-01-01
    • 2022-01-19
    相关资源
    最近更新 更多