最近想用SSM开发一个图片上传的功能,找了一遍网上的资料总觉得残缺不全,今天把个人的实现方式分享一下,同时做一个记录。
一、环境配置
1.准备JAR包
链接:https://pan.baidu.com/s/1yG1mXBADS3oaLi3eZL7HRA
提取码:rxg2
2.环境配置
spring_config.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<context:component-scan
base-package="com.spring.serviceimpl,com.spring.controller" />
<bean id="dataSource"
class="com.mchange.v2.c3p0.ComboPooledDataSource">
<!-- 数据库驱动JDBC -->
<property name="driverClass" value="com.mysql.jdbc.Driver" />
<!-- 数据库URL -->
<property name="jdbcUrl"
value="jdbc:mysql://localhost:3306/ssm?useUnicode=true&characterEncoding=utf8&useSSL=false" />
<!-- 用户名 -->
<property name="user" value="root" />
<!-- 密码 -->
<property name="password" value="123456" />
<!-- 连接池初始大小 -->
<property name="initialPoolSize" value="10" />
<!-- 连接池最大值 -->
<property name="maxPoolSize" value="20" />
<!-- 连接最大静默时间 单位为秒 -->
<property name="maxIdleTime" value="30" />
</bean>
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 依赖注入配置好的数据源 -->
<property name="dataSource" ref="dataSource"/>
</bean>
<tx:annotation-driven />
<bean id="sqlSessionFactory"
class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 依赖注入数据源 -->
<property name="dataSource" ref="dataSource"/>
<!-- 别名的Package ,URL: org.apache.ibatis.type -->
<property name="typeAliasesPackage" value="com.spring.entity" />
<!-- mybatis Annotation的包 (映射类) -->
<property name="typeHandlersPackage" value="com.spring.dao" />
<!-- 配置mapper.xml文件扫描 -->
<property name="mapperLocations" value="mapper/*.xml"/>
<property name="plugins">
<array>
<bean class="com.github.pagehelper.PageInterceptor">
<property name="properties">
<value>
params=value1
</value>
</property>
</bean>
</array>
</property>
</bean>
<!--这里拿一个模块来实例-->
<bean id="articleDao"
class="org.mybatis.spring.mapper.MapperFactoryBean">
<!-- 依赖注入配置好的Mybatis -->
<property name="sqlSessionFactory" ref="sqlSessionFactory" />
<!-- UserInfoDao接口 -->
<property name="mapperInterface"
value="com.spring.dao.ArticleDao" />
</bean>
</beans>
spring_MVC.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:component-scan
base-package="com.spring.controller" />
<mvc:default-servlet-handler />
<mvc:annotation-driven />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- view处理类 -->
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<!-- 前缀 -->
<property name="prefix" value="/" />
<!-- 后缀 -->
<property name="suffix" value=".jsp" />
</bean>
<!-- 配置multipartResolver文件解析器,文件上传的关键配置 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 设置上传文件的大小 -->
<property name="maxUploadSize" value="52428800" />
<!-- 设置默认编码 -->
<property name="defaultEncoding" value="utf-8" />
</bean>
</beans>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">
<display-name>SSM</display-name>
<welcome-file-list>
<welcome-file>login.jsp</welcome-file>
</welcome-file-list>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring_config.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>springMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- SpringMVC配置文件路径 -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring_MVC.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>springMVC</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
二、代码实现
基于SSM的图片上传功能无需在dao层和service层写任何方法,只需在controller层写入
Controller层
@Controller
@RequestMapping(value = "/FileUpload")
public class FileUploadController {
//这里的service只是一个增加信息的模块,和图片上传没有关系
@Autowired
private ArticleService articleService;
@RequestMapping(value = "/insertArticle")
public void addInfo(MultipartFile file, Article article, HttpServletRequest request) {
String fileName = file.getOriginalFilename();
//该路径是你要把图片上传到哪个文件夹的路径,我这里是上传到本项目的images文件夹中
String path = "D:\\IdeaWorkbench\\MyProject\\SSM\\WebContent\\images";
File f = new File(path);
if (!f.exists()){
f.mkdirs();
}
if (!file.isEmpty()){
try {
FileOutputStream fos = new FileOutputStream(path + "/" + fileName);
InputStream in = file.getInputStream();
int len = -1;
byte[] data = new byte[1024];
while ((len = in.read(data)) != -1){
fos.write(data, 0, len);
}
in.close();
fos.close();
}catch (Exception e){
e.printStackTrace();
}
}
if (fileName.endsWith(".jpg") || fileName.endsWith(".png") || fileName.endsWith(".gif")){
article.setImages("/images/" + fileName);
articleService.insertArticle(article);
}
}
}
FileUpload.jsp
<form id="infoForm" enctype="multipart/form-data" method="post"
class="am-form tpl-form-line-form" action="${pageContext.request.contextPath}/FileUpload/insertArticle">
<div class="am-form-group">
<label for="user-weibo" class="am-u-sm-3 am-form-label">封面图</label>
<div>
<input id="images" name="file" type="file">
</div>
</div>
<div class="am-form-group">
<div class="am-u-sm-9 am-u-sm-push-3">
<button onclick="formSubmit()" type="button" class="am-btn am-btn-primary tpl-btn-bg-color-success ">提交</button>
</div>
</div>
</form>
<script type="text/javascript">
function formSubmit() {
$("#infoForm").submit();
}
</script>
三、功能实例
选择恶灵骑士这一张图片
可以看到我文件夹下没有恶灵骑士的图片
点击上传之后
同时数据库也有记录了