How to load file from computer OR from URL

Viewed 1421

I have an webapp, that takes JSON file and parses it into objects. My goal is to make an user capable of uploading a file from their local computer or from a URL.

My index JSP page looks like this:

<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 looks like this

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 upload it from local computer it works so well, but when I try to do it with URL I get 500 Error (java.io.FileNotFoundException). I believe it's because the system still tries to find it like a local file on computer. How can I solve it?

1 Answers

The exception is coming from FileUtils.copyURLToFile. The JavaDoc for this method says this can occur for the following reasons:

  1. If source URL cannot be opened
  2. If destination is a directory
  3. If destination cannot be written
  4. If destination needs creating but can't be
  5. If an IO error occurs during copying

I reckon the two most likely candidates are #3 and #4. You probably don't have access to write to that directory. Add a try-catch around the FileUtils method and log the problem.

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
}
Related