码迷,mamicode.com
首页 > 编程语言 > 详细

springmvc上传文件踩过的坑

时间:2017-07-22 14:33:16      阅读:177      评论:0      收藏:0      [点我收藏+]

标签:ict   erp   indexof   tco   网页   ssi   数据   attr   string   

 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)

springmvc上传文件踩过的坑

标签:ict   erp   indexof   tco   网页   ssi   数据   attr   string   

原文地址:http://www.cnblogs.com/xinyang/p/7221047.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!