1

I need to dowload a file .json from my application, but to choose its location.

  • I know how to download a file to disk, like for an image <p:fileDownload value=""/>

    public StreamedContent getFile(){
        return new DefaultStreamedContent(stream, "image/jpg", "img.jpg"); 
    }
    
  • I know how to write to file with GSON with given path

    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(...){...}
    

But I do not know how to combine both to be able to choose the location and write the json at this location ?

azro
  • 53,056
  • 7
  • 34
  • 70

1 Answers1

1

So I don't think you can do what you want. All you can do is stream your JSON file and give it a name like "test.json". For security reasons you are not allowed to tell the browser WHERE you want the user to download. I believe it is similar to this request: Browsing file system to select directory in JSF

If however you just want to send a GSON file allowing the user to download it.

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;
   }
Melloware
  • 10,435
  • 2
  • 32
  • 62