文件上传
上传文件依赖的jar包
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.5</version>
</dependency>
加入上传文件所需的Bean
在配置文件spring-mvc.xml 加入
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="209715200" />
<property name="defaultEncoding" value="UTF-8" />
<property name="resolveLazily" value="true" />
</bean>
Controller
PicController.java
package com.xwx.controller;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import com.xwx.model.Pic;
import com.xwx.service.PicService;
@Controller
@RequestMapping("/pic")
public class PicController {
@Autowired
private PicService picService;
public PicService getPicService() {
return picService;
}
public void setPicService(PicService picService) {
this.picService = picService;
}
@RequestMapping("/add")
public String add(HttpServletRequest request){
return "pic/add";
}
@RequestMapping("/doAdd")
public String doAdd(HttpServletRequest request, @RequestParam(value="pic", required=true) MultipartFile pic){
String fileName = pic.getOriginalFilename();
String ext = fileName.substring(fileName.lastIndexOf(".") + 1);
//文件路径
String path = "D:\\upload\\123\\";
//文件名称
String newFileName = new Date().getTime() + "." + ext;
File targetFile = new File(path, newFileName);
if(!targetFile.exists()){
//创建目录
targetFile.mkdirs();
}
try {
//生成图片
pic.transferTo(targetFile);
/** 写入数据库
Date createTime = new Date();
Pic picModel = new Pic();
picModel.setPic(newFileName);
picModel.setCreateTime(createTime);
picService.insert(picModel);
**/
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
jsp
pic/add.jsp
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>add</title>
</head>
<body>
<c:if test="${errors != null}">
<div style="color:red">
<c:forEach items="${errors}" var="error">
<p>${error.defaultMessage}</p>
</c:forEach>
</div>
</c:if>
<form action="${pageContext.request.contextPath }/pic/doAdd.do" method="post" enctype="multipart/form-data">
<p>
<input type="file" name="pic">
</p>
<p>
<input type="submit" name="" value="提交">
</p>
</form>
</body>
</html>