【问题标题】:How to load file from computer OR from URL如何从计算机或 URL 加载文件
【发布时间】:2017-09-16 19:43:56
【问题描述】:

我有一个 webapp,它接受 JSON 文件并将其解析为对象。我的目标是让用户能够从本地计算机或 URL 上传文件。

我的索引 JSP 页面如下所示:

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

控制器类如下所示

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

当我尝试从本地计算机上传它时效果很好,但是当我尝试使用 URL 上传时,我得到 500 错误 (java.io.FileNotFoundException)。我相信这是因为系统仍然试图像计算机上的本地文件一样找到它。我该如何解决?

【问题讨论】:

标签: java json spring-mvc


【解决方案1】:

异常来自FileUtils.copyURLToFileThe JavaDoc for this method 说这可能是由于以下原因:

  1. 如果无法打开源 URL
  2. 如果目标是目录
  3. 如果无法写入目的地
  4. 如果目标需要创建但不能创建
  5. 如果在复制过程中发生 IO 错误

我认为最有可能的两个候选人是#3 和#4。您可能无权写入该目录。在 FileUtils 方法周围添加一个 try-catch 并记录问题。

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
}

【讨论】:

  • 鉴于 OP 在 web 框架中工作,最好将日志记录添加到框架本身为错误处理提供的任何钩子中。记录故障的最佳位置通常位于(或在框架的情况下略高于)代码的边界处。将它直接放在调用周围可能会导致错误地吞下错误,因为可能会忘记重新抛出,并且重新抛出可能会导致重复记录。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-06
  • 1970-01-01
相关资源
最近更新 更多