1.导入jar包(commons-io-1.4.jar和commons-fileupload-1.2.1.jar)
2.在springmvc.xml配置文件中添加上传文件解析器
<bean name="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 设置上传文件的大小5M -->
<property name="maxUploadSize" value="5242880"></property>
</bean>
3.创建文件上传实现类
import java.io.File;
import java.io.IOException;
import org.springframework.web.multipart.MultipartFile;
public class UploadUtils {
public static String upload(MultipartFile file) {
try {
//定义上传的位置
String path ="e:upload/";
File filePath = new File(path);
if(!filePath.exists()) {//如果目录不存在,创建目录
filePath.mkdir();//这个函数只允许创建一层目录,mikdirs()可以创建多层
}
file.transferTo(new File(path));//上传文件
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "上传成功";
}
}
3.在jsp页面设置标签
<input name="imgpic" type="file" value="">
<a href=""${pageContext.request.contextPath }/upload">上传</a>
4.controller网页调用方法
@RequestMapping("/upload")
public String (MultipartFile imgpic) {
String upload = UploadUtils.upload(imgpic);
System.out.println(upload);
return "index";
}