zoukankan      html  css  js  c++  java
  • 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)

  • 相关阅读:
    python基础知识第三篇(列表)
    python基础知识第二篇(字符串)
    python基础知识第一篇(认识Python)
    tomacat环境搭建
    Python的内存管理机制
    selenium定位方法
    python+selenium xpath定位
    django--创建及配置项目app
    django--cookies和session
    django--orm--012
  • 原文地址:https://www.cnblogs.com/xinyang/p/7221047.html
Copyright © 2011-2022 走看看