I am returning an object as json through the existing rest service, however I wish to save the json to the users local disk.
            Asked
            
        
        
            Active
            
        
            Viewed 1,101 times
        
    1
            
            
        - 
                    possible duplicate of https://stackoverflow.com/questions/1053467/how-do-i-save-a-string-to-a-text-file-using-java – Scary Wombat Jun 29 '17 at 07:04
- 
                    see also https://stackoverflow.com/questions/3802510/force-to-open-save-as-popup-open-at-text-link-click-for-pdf-in-html – Scary Wombat Jun 29 '17 at 07:06
- 
                    or https://stackoverflow.com/questions/11353425/force-a-browser-to-save-file-as-after-clicking-link – Scary Wombat Jun 29 '17 at 07:06
3 Answers
0
            You can write the file in the server. And use the following code to send the file to user.
String path = context.getSession().getServletContext().getRealPath("/") + "path to file";  
InputStream inputStream = prepairFileStream(response, path);
if (inputStream == null) return;
FileCopyUtils.copy(inputStream, response.getOutputStream());
 
    
    
        Lakmal Vithanage
        
- 2,767
- 7
- 42
- 58
0
            
            
        Only the user can choose to save a file on their local disk.
You can advise a browser (provided that a browser is involved on the user's side) to prompt the user with a "Save As..." dialog by including a Content-Disposition header with your response:
Content-Disposition: attachment; filename="fname.json"
 
    
    
        shinobi
        
- 351
- 1
- 8
0
            
            
        You can do something like this:-
testFunction: function(req, res){
var yourJson = {"test":"testing"};
var text={"filename.txt":yourJson};
res.set({'Content-Disposition': 'attachment;filename=\"cards.txt\"','Content-type': 'text/plain'});
res.send(text['filename.txt']);
}
this will download your json data as a file in your downloads folder.
 
    
    
        Ankit0047
        
- 144
- 1
- 10
