1.编写jsp页面
<form action="upload" enctype="multipart/form-data" method="post">
名称:<input type="text" name="name"><br />
文件:<input type="file" name="file"><br />
<input type="submit" value="提交" />
</form>
2.在springMVC配置文件spring.xml中添加MultiparterResovler解析器
<!--MultipartResovler解析器-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
</bean>
3.编写控制器类
(1)MultipartFile 对象名必须和的name属性名相同
(2)需要额外导入apache文件上传commons-fileupload和conmons-io两个jar
@RequestMapping("upload")
public String upload(MultipartFile file,String name) throws IOException {
String fileName = file.getOriginalFilename();
String suffix = fileName.substring(fileName.lastIndexOf("."));
//判断文件上传类型
if(suffix.equalsIgnoreCase(".png")){
String uuid = UUID.randomUUID().toString();
FileUtils.copyInputStreamToFile(file.getInputStream(), new File("D:/" + uuid + suffix));
return "index";
}else{
return "error";
}
}
来源:CSDN
作者:Mkk丶
链接:https://blog.csdn.net/weixin_44925278/article/details/104264938