标签:
5.文件上传
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"; }
标签:
原文地址:http://www.cnblogs.com/winner-0715/p/4966195.html