【问题标题】:How to download file directly from browser with Spring Boot如何使用 Spring Boot 直接从浏览器下载文件
【发布时间】:2019-06-24 16:01:23
【问题描述】:

我正在尝试创建一个在 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);
    }
}

【问题讨论】:

    标签: spring file spring-boot download


    【解决方案1】:

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

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

    现在,如您所见,您只传递文件名(没有任何路径)。您只需要添加路径到您的客户端下载文件夹。像这样的东西在 mac 和 linux 上对我有用:

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

    【讨论】:

      猜你喜欢
      • 2011-12-19
      • 1970-01-01
      • 1970-01-01
      • 2016-04-22
      • 2014-07-09
      • 1970-01-01
      • 1970-01-01
      • 2023-03-21
      • 1970-01-01
      相关资源
      最近更新 更多