如何使用Spring Boot从浏览器直接下载文件

时间:2019-06-21 15:44:32

标签: spring file spring-boot download

我正在尝试创建一个应用程序,该应用程序在进行JSON解析后会从URL下载文件,但它是在应用程序目录而不是客户端的下载文件夹中下载文件。 有人可以帮我了解如何做到吗?

这是我的代码:

@RequestMapping(value = "/", method = RequestMethod.GET)
public String getSteamingFile() throws Exception { //get method

  File f = new File("t1.csv");

  if(!f.exists() && !f.isDirectory()){

    try {

         URLConnection openConnection = new URL("https://www.dati.gov.it/api/3/action/package_show?id=537c1138-4c5f-41bb-aec8-862954b67b28").openConnection();
         openConnection.addRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:25.0) Gecko/20100101 Firefox/25.0");
         InputStream in = openConnection.getInputStream();

         String data = "";
         String line = "";
         try {
           InputStreamReader inR = new InputStreamReader(in);
           BufferedReader buf = new BufferedReader(inR);

           while (( line = buf.readLine()) != null) {
               data+=line;
               System.out.println(line);
           }

         } finally {
           in.close();
         }

        JSONObject obj = (JSONObject) JSONValue.parseWithException(data); 
        JSONObject objI = (JSONObject) (obj.get("result"));
        JSONArray objA = (JSONArray) (objI.get("resources"));

        for(Object o: objA){ //json parse to get the url
            if (o instanceof JSONObject) {
                JSONObject o1 = (JSONObject)o; 
                String format = (String)o1.get("format");
                String urlA = (String)o1.get("url");
                urlA = urlA.replaceAll("&","&");
                URL urlD = new URL (urlA);
                System.out.println(format + " | " + urlD);
                if(format.equals("csv")) {
                    File fname = new File ("t1.csv");
                    download(urlD, fname);
                }
            }
        }
        System.out.println( "OK" );
    } catch (IOException e) {
        e.printStackTrace();
    }
}
  else System.out.println("File presente, impossibile scaricare");

  return "index";}

public static void download(URL url, File fileName) {
    try {
        FileUtils.copyURLToFile(url, fileName);     
    } catch (IOException e) {
        System.out.println("Errore di Input/Output" + e);
    }
}

1 个答案:

答案 0 :(得分:0)

这是您必须进行更改的地方:

File fname = new File ("t1.csv");

现在,您可以看到,您仅传递文件名(没有任何路径)。您只需要将路径添加到客户端的Downloads文件夹。像这样的东西在Mac和Linux上对我有用:

File fname = new File ("~/Downloads/t1.csv");