相关知识:
1. MultipartResovler: 文件上传解析器.
1.1 将文件以文件流的形式包装到请求中,然后通过请求上传到 服务器
1.1 作用:把请求对象中文件内容解析成MultipartFile对象.
1.2 一个文件域(<input type=”file”)对应一个MultipartFile对象.
1.3 SpringMVC默认没有MultipartResovler对象的.
2. SpringMVC 文件上传基于apache的commons-fileupload.
3. jsp表单中如果希望上传文件流
3.1 enctype=”multipart/form-data” 允许上传文件流
3.1.1 enctype="application/x-www-form-urlencoded" 默认值,表示上传普通表单表单数据,数据中包含字符串数据
3.1.2 enctype=”text/plain” 邮箱,大文本数据.文字内容.
3.2 method=”post”
3.2.1 因为post是字节流
3.2.2 因为post传输数据量大(2GB)
1.编写前端页面
<form action="register" method="post" style="padding-top: 0;" id="nextform" enctype="multipart/form-data">
<p style="font-size: 20px;font-weight: 600;margin-top: 10px;">申请账号</p>
<ul class="editInfos" style="width: 90%;margin: 0 auto;margin-top:-15px;">
<li><span>头象 </span> <input name="photo_file" type="file"/></li>
<li><span>用户名 </span> <input type="text" name="user_name" placeholder="用户名"/></li>
<li><span>密码 </span> <input type="password" name="password" placeholder="密码"/></li>
<li><span>身份 </span> <input type="text" name="identity" placeholder="学生/教师/职员"/></li>
<li><span>院校 </span> <input type="text" name="school" placeholder="填写您所就读的院校"/></li>
<li><span>专业 </span> <input type="text" name="major"placeholder="填写您所就读的专业"/></li>
<li><span>联系方式</span> <input type="text" name="contact_number" placeholder="通讯方式(电话/QQ/微信)"/></li>
</ul>
<input class="btn" style="width: 40%;height:35px;margin: 0 auto;line-height: 18px;background-color: gainsboro;cursor:pointer;color: black;margin-top: 15px;border-radius: 5px;font-size: 18px;text-align: center;" value="提交申请"/>
</form>
2.配置springmvc.xml文件
在springmvc.xml配置文件上传解析器,springmvc中有文件解析的功能。
2.1 必须有id,且必须叫multipartResolver
2.2 maxUploadSize 最大上传文件大小,单位byte
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="90"></property>
</bean>
3.配置Action
@RequestMapping(name="register")
public String registerUser(MultipartFile photo_file, User user,HttpServletRequest req) throws IOException{
String originalName = photo_file.getOriginalFilename();//获得原始的文件名 文件名.类型(cute.jpg)
String fileType = originalName.substring(originalName.indexOf(".")+1);
String uuid = UUID.randomUUID().toString().replace("-", "");
String photo_address = uuid+"."+fileType;
user.setPhoto_address(photo_address);
// 上传到服务器
InputStream is = photo_file.getInputStream();
String absolutePath = req.getServletContext().getRealPath("WEB-INF/photo");
String newFile = absolutePath+"\\"+photo_address;
File file = new File(newFile);
FileUtils.copyInputStreamToFile(is, file);
int count = userService.registerUser(user);// 存放在数据库
System.out.println(count);
return "forward:login.jsp";
}