总共分三步:
第一步:在springmvc-servlet.xml 添加如下代码:
<!--
========================华丽的分割 文件上传==================================
-->
<!--id="multipartResolver" 不能随便写-->
<!--同时在jsp页面 在form表单里面添加一个属性 enctype="multipart/form-data" -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!--maxUploadSize:文件上传的单位是byte为单位 比如2兆 就是2097152 -->
<property name="maxUploadSize" value="2097152"></property>
</bean>
第二步:Jsp页面在Form表单里面添加属性 enctype="multipart/form-data"
第三步:在Controller添加代码
// =============================以下是文件上传=========================================
/**
* @throws Exception
*
* @Title: upLoadFile
* @Description: 上传一个图片到upload文件夹
* @param @return 设定文件
* @return String 返回类型
* @throws
*/
@RequestMapping("/upLoadFile.do")
public String upLoadFile(HttpServletRequest request) throws Exception {
/**
* 第一步转化request
*/
MultipartHttpServletRequest rm = (MultipartHttpServletRequest) request;
/**
* 获得文件rm.getFile("pic");参数就是jsp里面定义的file input标签的name
*/
CommonsMultipartFile cFile = (CommonsMultipartFile) rm.getFile("pic");
/**
* 获得文件的字节数组
*/
byte[] b = cFile.getBytes();
String fileName = "";
/**
* 获得当前时间的最小精度 小时分钟秒 三个S代表三个随机数
*/
SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmssSSS");
fileName = format.format(new Date());
/**
* 产生三个随机数
*/
Random random = new Random();
for (int i = 0; i < 3; i++) {
// 0-9之间做随机数
fileName = fileName + random.nextInt(9);
}
/**
* 获得原始文件名
*/
String origFileName = cFile.getOriginalFilename();
/**
* xxxx.jpg 拿到文件后缀名
*/
String suffix = origFileName.substring(origFileName.lastIndexOf("."));
/**
* 拿到上传路径
*/
String path = request.getSession().getServletContext().getRealPath(
"upload");
/**
* 定义文件的输出流
*/
OutputStream out = new FileOutputStream(new File(path + "/upload"
+ fileName + suffix));
out.write(b);
out.flush();
out.close();
return "index";
}
/**
*
* @Title: toUpLoad
* @Description: 跳转到upLoad.jsp
* @param @return 设定文件
* @return String 返回类型
* @throws
*/
@RequestMapping("/toUpload.do")
public String toUpLoad() {
return "upLoad";
}