spring mvc配置文件代码
<!-- 组件扫描 只扫描action -->
<context:component-scan base-package="com.trace.action" />
<!-- 使用<mvc:annotation-driven />替换上边定义的处理器映射器和适配器 -->
<mvc:annotation-driven />
<!-- 视图解析器 解析jsp视图,默认使用jstl,要求classpath下有jstl的jar包 -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 视图的前缀 -->
<property name="prefix" value="/WEB-INF/jsp/" />
<!-- 视图的后缀 -->
<property name="suffix" value=".jsp" />
</bean>
<!-- 另外最好还要加入DefaultAnnotationHandlerMapping,不然会被 XML或其它的映射覆盖! -->
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />
<!-- 上传功能 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>
上传Action方法
@RequestMapping(value = "/upload")
public String upload(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request, ModelMap model) {
System.out.println("开始");
String path = request.getSession().getServletContext().getRealPath("image");
String fileName = file.getOriginalFilename();
// String fileName = new Date().getTime()+".jpg";
//path:保存路径,fileNmae:文件名称
System.out.println("保存路劲为"+path);
File targetFile = new File(path, fileName);
if(!targetFile.exists()){
targetFile.mkdirs();
}
try {
//写入文件
file.transferTo(targetFile);
} catch (Exception e) {
e.printStackTrace();
System.out.println("保存失败");
}
//向前台传送数据
model.addAttribute("fileUrl", request.getContextPath()+"/image/"+fileName);
return "result";
}
最终效果
上传成功