zoukankan      html  css  js  c++  java
  • spring mvc上传图片

    1、需要commons-fileupload.jar

    commons-io.jar

    2、需要在springmvc.xml中 配置存放静态资源的路径,对图片等静态资源放行

         <mvc:resources location="/static/" mapping="/static/**"/>

    3、图片上传页面

     <form action="/springmvc1/upload" method="post" enctype="multipart/form-data">
            <input type="text" name="title"/><br>
            <input type="file" name="file"/><br>
            <input type="submit">
        </form>
        <img alt="图片" src=${imgpath }>

    4、后台页面

    @RequestMapping(method=RequestMethod.GET)
        public String upload(){
            return "fileupload";
        }
        
        @RequestMapping(method=RequestMethod.POST,produces="text/html;charset=UTF-8")
        public String uploadPost(String title, MultipartFile file, HttpServletRequest request, RedirectAttributes redirectAttributes){
            
            String realPath=null;
            
            String filename = UUID.randomUUID().toString()+"."+file.getOriginalFilename().split("\.")[1];
            try {
                
                realPath = request.getSession().getServletContext().getRealPath("/static/upload/");
                file.transferTo(new File( realPath + File.separatorChar + filename));
            } catch (IllegalStateException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            redirectAttributes.addFlashAttribute("imgpath", "/springmvc1/static/upload/" + filename);
            return "redirect:/upload";
        }

    通过url请求时:

    上传成功后

    可以再xml配置上传文件大小的限制:

         <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
             <property name="maxUploadSize" value="100000"></property>
         </bean>

    上传过大的就会报出异常。

  • 相关阅读:
    hdu 1269 迷宫城堡 (并查集)
    hdu 1272 小希的迷宫 (深搜)
    hdu 1026 Ignatius and the Princess I (深搜)
    hdu 1099 Lottery
    hdu 1068 Girls and Boys (二分匹配)
    几个基础数位DP(hdu 2089,hdu 3555,uestc 1307 windy 数)
    hdu 1072 Nightmare (广搜)
    hdu 1398 Square Coins (母函数)
    hdu 1253 胜利大逃亡 (深搜)
    hdu 1115 Lifting the Stone (求重心)
  • 原文地址:https://www.cnblogs.com/hpustudent/p/4319431.html
Copyright © 2011-2022 走看看