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

这样,在页面显示的时候,就可以使用

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

posted @ 2017-07-22 12:59  天边的鱼  阅读(672)  评论(0编辑  收藏  举报