版权声明:ByRisonBoy https://blog.csdn.net/Rison_Li/article/details/82953664
代码片段:
//新增post
@RequestMapping(method=RequestMethod.POST, value="/addPost")
@ResponseBody
public int addPost(Post post, MultipartFile file, HttpSession session) {
try {
if(file.getSize() > 0) {
String path = session.getServletContext().getRealPath("upload/postImg/");//绝对路径
System.out.println(path);
File targetFile = new File(path, file.getOriginalFilename());
file.transferTo(targetFile);
String p = path+file.getOriginalFilename();
System.out.println(p);
post.setPostImg(file.getOriginalFilename());
System.out.println(post.getPostImg());
System.out.println(post);
}
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(post);
return this.postService.addPost(post);
}
springmvc-config.xml配置:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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-4.3.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd">
<!-- 配置包扫描器,扫描@Controller注解的类 -->
<context:component-scan base-package="com.book.controller" />
<!-- 加载注解驱动 -->
<mvc:annotation-driven />
<!-- 注册适配器 -->
<!-- 配置视图解析器 -->
<!-- 访问静态文件 -->
<mvc:annotation-driven />
<mvc:resources location="/upload/" mapping="/upload/**"/>
<mvc:resources location="/js/" mapping="/js/**"/>
<mvc:resources location="/css/" mapping="/css/**"/>
<!-- 支持文件上传 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="104857600" />
<property name="maxInMemorySize" value="4096" />
<property name="defaultEncoding" value="UTF-8"></property>
</bean>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
本例用到了SSM框架知识,不懂得朋友可以先去了解SSM的相关知识,往后我会补上SSM的整个详细搭建流程。