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

spring mvc文件上传

时间:2015-11-15 10:47:48      阅读:302      评论:0      收藏:0      [点我收藏+]

标签:

5.文件上传

  1. 引入jar包

技术分享

  2. 配置视图解析器

<!-- id不能自命名,必须是multipartResolver -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!--maxUploadSize上传文件的最大值,以byte为单位  -->
        <property name="maxUploadSize" value="1024000"></property>
    </bean>

jsp:

<form action="test/toPerson7.do" method="post" enctype="multipart/form-data">
        name:<input name="name" type="text"><br>
        age:<input name="age" type="text"><br>
        address:<input name="address" type="text"><br>
        birthday:<input name="birthday" type="text"><br>
        pic:<input  type="file" name="pic"><br>
        
        <input type="submit" value="submit"><br>
    </form>

 3.写上传逻辑

@RequestMapping(value="/toPerson8.do")
    public String toPerson8(Person person,HttpServletRequest request) throws Exception{
        //第一步转化request
        MultipartHttpServletRequest rm = (MultipartHttpServletRequest) request;
        //获得文件
        CommonsMultipartFile cfile = (CommonsMultipartFile) rm.getFile("pic");
        //获得文件的字节数组
        byte[] bfile = cfile.getBytes();
        String fileName = "";
        //获得当前时间的最小精度
        SimpleDateFormat format =  new SimpleDateFormat("yyyyMMddHHmmssSSS");
        fileName = format.format(new Date());
        //获得三位随机数
        Random random = new Random();
        for(int i = 0; i < 3; i++){
            fileName = fileName + random.nextInt(9);
        }
        //获得原始文件名
        String origFileName = cfile.getOriginalFilename();
        //XXX.jpg
        String suffix = origFileName.substring(origFileName.lastIndexOf("."));
        //拿到项目的部署路径
        String path = request.getSession().getServletContext().getRealPath("/");
        //定义文件的输出流
        OutputStream out = new FileOutputStream(new File(path+"/upload/"+fileName+suffix));
        out.write(bfile);
        out.flush();
        out.close();
        
        return "jsp1/index";
    }

 

spring mvc文件上传

标签:

原文地址:http://www.cnblogs.com/winner-0715/p/4966195.html

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