【问题标题】:Contents and format of URI when uploading or downloading file上传或下载文件时URI的内容和格式
【发布时间】:2021-12-06 14:05:42
【问题描述】:

我有一个应用程序,它是服务器上的一个 API(比如 192.168.0.2),可以将文件(任何格式)上传到或从中下载。

如果网络上另一台机器(例如 192.196.0.3)上的应用程序想要将文件上传到 API,它会以 JSON 对象的形式传递信息,例如{ "FILE_LOCATION":"file:/192.168.0.3/c:/testDocs/testFile.docx" }

api中的代码大致如下:

private static void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
    String errorMessage = "";
    try
    {
        String src = request.getParameter ("src");
        Object obj = jsonParser.parse (src);
        JSONObject jsonObj = (JSONObject) obj;

        String fileLocation = (String) jsonObj.get ("FILE_LOCATION");
        URI uri = new URI (fileLocation);
        URL url = uri.toURL ();    // get URL from your uri object
        URLConnection urlConnection = url.openConnection ();
        InputStream is = urlConnection.getInputStream ();

        System.out.println ("InputStream = " + is);
        if (is != null)
        {
            // create output file, output stream etc
        }
    }
    catch (Exception e)
    {
        errorMessage = e.getMessage ();
        System.out.println (e.getClass().getName () + " : " + errorMessage);
    }

    PrintWriter pw = response.getWriter ();
    pw.append (errorMessage);
}

系统日志总是显示如下内容: "java.io.FileNotFoundException : 192.168.0.3/c:/testDocs/testFile.docx (没有这样的文件或目录)"

我做错了什么?我确信错误在于我构建将用于创建 URI 的字符串的方式。

【问题讨论】:

    标签: java upload uri


    【解决方案1】:

    这看起来不像是一个有效的file: URL。在 Windows 上,如果 dirCMD.EXE 中工作,您可以尝试检查文件是否可以从远程服务器访问。例如,试试 UNC 路径名:

    dir \\IP_OR_HOSTNAME\NAMEOFSHARE\path\etc\filename.xyz
    

    如果有效——这取决于远程服务器是否以NAMEOFSHARE 为该文件系统提供服务——那么上面等效的file: 编码将是:

    String u = new File("\\\\IP_OR_HOSTNAME\\NAMEOFSHARE\\path\\etc\\filename.xyz").toURL().toString();
    ==> "file://IP_OR_HOSTNAME/NAMEOFSHARE/path/etc/filename.xyz"
    

    【讨论】:

    • 谢谢。我要发送的是; "file://[IP 地址]/[监听端口号]/[驱动器:]/[路径]/文件名。这还有效吗?
    • 这看起来不像是 Windows 主机有效文件协议的格式(我也不认为 Windows 机器将它们的 drive: 字母暴露给其他服务器)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-20
    • 2021-06-21
    • 1970-01-01
    • 2017-10-06
    • 2013-10-06
    • 1970-01-01
    相关资源
    最近更新 更多