[英]Contents and format of URI when uploading or downloading file
我有一個應用程序,它是服務器上的 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 的 String 的方式。
這看起來不像一個有效的file:
URL。 在 Windows 上,如果dir
在CMD.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"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.