springmvc上傳文件踩過的坑

 1     @RequestMapping("/addTweet")
 2     public String addTweet(TweetVO tweetVO, HttpServletRequest request, Model model,
 3                            @RequestParam(value = "file", required = false) MultipartFile file) {
 4         try {
 5             String pathRoot = String.valueOf(request.getSession().getServletContext().getRealPath("/"));
 6             String path = "";
 7             if (!file.isEmpty()) {
 8                 // 生成uuid做爲文件名稱
 9                 String uuid = UUID.randomUUID().toString().replaceAll("-", "");
10                 // 得到文件類型(能夠判斷若是不是某種類型,禁止上傳)
11                 String contentType = file.getContentType();
12                 // 得到文件後綴名稱
13                 String imageName = contentType.substring(contentType.indexOf("/") + 1);
14                 path = "/static/image/" + uuid + "." + imageName;
15                 file.transferTo(new File(pathRoot + path));
16                 request.setAttribute("imagesPath", path);
17 //                model.addAttribute("imagesPath", path);
18                 tweetVO.setPicture(path);
19                 tweetService.addTweet(tweetVO);
20             }
21         } catch (Exception e) {
22             e.printStackTrace();
23         }
24         return "redirect:/tweet/list";
25     }

在transferTo中,使用的是絕對路徑 pathRoot + path,可是在數據庫中存儲的時候,使用的是相對路徑 path數據庫

這樣,在頁面顯示的時候,就可使用windows

<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() +
            ":" + request.getServerPort() + path + "/";
    request.setAttribute("path", path);
    request.setAttribute("basePath", basePath);
%>
<img src="${basePath}${tweet.key.picture}" alt="${basePath}${tweet.key.picture}"/>

其中basePath表示的是服務器路徑http://localhost:8080/bignews1/ ,tweet.key.picture表示的是以前的數據庫裏面存儲的相對路徑,這樣就能顯示出圖片了。服務器

注意,不能在數據庫中直接存儲絕對路徑,例如c:\\windows\\system32這種,若是在網頁裏面直接請求這個路徑,會報錯(not allowed to load local resource)app

相關文章
相關標籤/搜索