做商城类项目,图片上传是一个不可或缺的功能,用io流写一个基本的图片到某个文件夹倒是也不难,但是实际应用的框架项目中时会有不少限制包括图片上传后的回显问题,很简单的东西,但是细节比较多,整理一下给大家分享一下,希望对大家有帮助
1. 引入依赖,修改配置文件
- pom.xml
<!-- 文件上传的依赖 -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
- springMVC.xml
<!-- 文件上传的解析器 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 上传图片的最大尺寸 10M -->
<property name="maxUploadSize" value="10485760"></property>
<!-- 默认编码 -->
<property name="defaultEncoding" value="utf-8"></property>
</bean>
- web.xml
<!--配置过滤器 -->
<filter>
<filter-name>encoding</filter-name>
<filter-class>com.xwz.global.EncodingFilter</filter-class>
<!--初始化参数 -->
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
</filter>
2. 前端页面
表单的提交方式必须是post类型,因为get提交的数据最大为1024个字节,还有必须加上enctype=“multipart/form-data”, 指定传输数据为二进制类型,不然后端接收不到
<form action="" method="post" enctype="multipart/form-data">
3. 控制器Controller
需要使用@RequestParam注解,使用MultipartFile 接收前端传递过来的图片文件
@RequestParam("image") MultipartFile file
4.编写一个使用io流将上传的文件保存项目指定路径中的工具方法
/**
* 将前端传递过来的图片保存到项目指定文件夹
*
* @author xuweizhi
* @date: 2021/12/23
* @time: 23:10
* @description: No Description
*/
public class IMG {
public String setImg(MultipartFile file) {
String newFileName = "";
try {
//获取当前项目路径
String classpath = this.getClass().getResource("/").getPath().replaceFirst("/", "");
classpath=classpath.replaceAll("/target", "&");
classpath=classpath.substring(0,classpath.indexOf("&"));
//获取当前服务器地址
String tomcatPath=System.getProperty("user.dir");
// 保存图片的路径,图片上传成功后,将路径保存到数据库
String filePath = classpath + "\\src\\main\\webapp\\images\\product";
// 获取原始图片的扩展名
String of = file.getOriginalFilename();
// 生成文件新的名字
Date date = new Date();
newFileName = date.getTime() + ".jpg";
// 封装上传文件位置的全路径
File targetFile = new File(filePath, newFileName);
file.transferTo(targetFile);
} catch (IOException e) {
e.printStackTrace();
}
return newFileName;
}
}
5.上传成功后的图片回显问题解决
根据上面的关键代码已经可以将图片上传功能实现了,其他的就是添加的一些sql将第四步工具方法的路径写到数据库就可以了,我这边不做赘述了,
完成上面的功能后你会发现,图片已经上传成功了,在项目路径里面也可以找到上传的图片,数据库里面也有图片的路径信息了,但是网页无法显示图片,需要你重启项目,也就是重启Tomcat才能看到图片,
因为你只是把图片写到项目的根路径里面,并没有将图片加载到Tomcat服务器上面,所以需要在idea中将Tomcat配置一下,将图片存放路径直接加载到Tomcat中,前端通过超链接访问图片,这样就可以解决图片的回显问题
<img height="77" width="77" src="http://localhost:8080//product/${book.image}" />