How to download a file from a computer or from a URL

I have a webapp that takes a JSON file and parses it into objects. My goal is to make it possible for a user to download a file from his local computer or URL.

My JSP index page is as follows:

<form method="post" action="products" enctype="multipart/form-data">
    Select a file from the computer <input type="file" name="file">
    <br>
    Or load from URL<input type="url" name="urlFile">
    <br>
<button type="submit">Parse</button>

The controller class is as follows:

public String parse(@RequestParam("file") MultipartFile file,
                    @RequestParam("urlFile") URL url,
                     Model model)
                     throws IOException, SAXException, ParserConfigurationException
{
    File convFile = null;

    if(file != null)
    {
        convFile = new File(file.getOriginalFilename());
        file.transferTo(convFile);
    }
    else if(url != null)
    {
        String tDir = System.getProperty("java.io.tmpdir");
        String path = tDir + "tmp" + ".xml";
        convFile = new File(path);
        convFile.deleteOnExit(); 
        FileUtils.copyURLToFile(url, convFile);
    }

    //... parsing JSON...
    return "products"
}

When I try to download it from the local computer, it works so well, but when I try to do it with the URL, I get 500 Error ( java.io.FileNotFoundException). I believe, because the system is still trying to find it as a local file on the computer. How can I solve it?

+4
source share
1 answer

FileUtils.copyURLToFile. JavaDoc , :

  • URL-
  • destination -
  • ,
  • -

, # 3 # 4. , . try-catch FileUtils .

String tDir = System.getProperty("java.io.tmpdir");
String path = tDir + "tmp" + ".xml";
convFile = new File(path);
convFile.deleteOnExit();
try {
    FileUtils.copyURLToFile(url, convFile);
}
catch (IOException e) {
    // log exception
}
+2

Source: https://habr.com/ru/post/1685804/


All Articles