参考文章
一、在SpringMVC.xml添加配置
<!--文件上传(文件或者图片)-->
<bean id ="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize">
<value>5242880</value>
</property>
</bean>
<!--labelImg存放图片文件夹,保证地址栏可以正常访问-->
<mvc:resources mapping="/labelImg/**" location="/labelImg/" />
二、前台form中提交**enctype=“multipart/form-data”**的数据
<form action="/labelController/saveLabel" method="post" enctype="multipart/form-data">
<div>
...
<input type="file" name = "imgFile">
...
</div>
</form>
三、后台controller
@RequestMapping(value = "saveLabel")
public String saveDepartment(HttpServletRequest request,Label label,MultipartFile imgFile)
{
try {
//label实体类的处理。。。
//操作成功后上传图片
//获取文件的原始名称
String originalFileName = imgFile.getOriginalFilename();
//上传图片
if(imgFile!=null && originalFileName!=null && originalFileName.length()>0)
{
//获取项目运行路径
String temp = servletContext.getRealPath("/");
//存储图片的物理路径
String imgPath =temp+ "labelImg/";
//新图片
File newFile = new File(imgPath+".png");
//将内存中的数据写入磁盘
imgFile.transferTo(newFile);
}
httpServletRequest.getSession(false).removeAttribute("token");
} catch (Exception e) {
...
}
return "返回信息";
}
以上就是本文全部内容,希望可以帮助到大家,如有问题,请留言(手动抱拳)。