鍍金池/ 問答/Java  HTML/ java后臺的“/”相對路徑不是代表webroot嗎,為什么在這里代表了d盤,測

java后臺的“/”相對路徑不是代表webroot嗎,為什么在這里代表了d盤,測試的文件都傳到了d盤呀?

圖片描述

@RequestMapping(value = "/upload_img",method = {RequestMethod.GET, RequestMethod.POST},produces = "application/json; charset=utf-8")
    @ResponseBody
    public String upload_img(MultipartFile file,HttpServletRequest request) throws Exception{
        String path="/upload/news";
        //創(chuàng)建文件 
        File dir=new File(path);
        if(!dir.exists()){
            dir.mkdirs();
        }
        String id = SysUtil.getUUID();
        String fileName=file.getOriginalFilename();
        String img=id+fileName.substring(fileName.lastIndexOf("."));//zhao.jpg
        FileOutputStream imgOut=new FileOutputStream(new File(dir,img));//根據(jù) dir 抽象路徑名和 img 路徑名字符串創(chuàng)建一個新 File 實例。
        imgOut.write(file.getBytes());//返回一個字節(jié)數(shù)組文件的內(nèi)容
        
        imgOut.close();
        Map<String, String> map=new HashMap<String, String>();
        map.put("path",img);
        return JSON.toJSONString(map);
    }
回答
編輯回答
情皺

/代表webroot是Web Server容器對某些操作的約定,比如forward方法等。但是在純Java中,也就是直接調(diào)用JDK的時候,/所表示的仍然是當(dāng)前盤符的根,而不是webroot。

這種情況一般都使用相對路徑來做,不要用絕對路徑。

2017年12月14日 23:36
編輯回答
六扇門

經(jīng)過測試:

new File(""); // 返回當(dāng)前項目路徑
new File("test.txt"); // 返回當(dāng)前項目路徑加上給定文件名
new File("/test.txt"); // 返回 `JVM` 實例所在盤符加上給定文件名

File.java 里可以看到其構(gòu)造方法的源碼:

// File.java
    public File(String pathname) {
        if (pathname == null) {
            throw new NullPointerException();
        }
        this.path = fs.normalize(pathname);
        this.prefixLength = fs.prefixLength(this.path);
    }

其中 path 就是影響到結(jié)果的地方,fsWindows 下是一個 WinNTFileSystem 的實例,其 normalize 方法的源碼如下:

    /* Check that the given pathname is normal.  If not, invoke the real
       normalizer on the part of the pathname that requires normalization.
       This way we iterate through the whole pathname string only once. */
    @Override
    public String normalize(String path) {
        int n = path.length();
        char slash = this.slash;
        char altSlash = this.altSlash;
        char prev = 0;
        for (int i = 0; i < n; i++) {
            char c = path.charAt(i);
            if (c == altSlash)
                return normalize(path, n, (prev == slash) ? i - 1 : i);
            if ((c == slash) && (prev == slash) && (i > 1))
                return normalize(path, n, i - 1);
            if ((c == ':') && (i > 1))
                return normalize(path, n, 0);
            prev = c;
        }
        if (prev == slash) return normalize(path, n, n - 1);
        return path;
    }

具體為什么 / 會導(dǎo)致結(jié)果的不同,現(xiàn)在我沒時間追下去,有興趣你可以自行看一下,這個文件在 java.io.WinNTFileSystem

那你就檢查 Tomcat(或者其他 Server) 的配置文件看一下 webroot 指向了哪里

2018年3月3日 08:16