jsp页面
<form method="post" name="myForm" action="saveUserEditInfo.w" id="userForm1" enctype="multipart/form-data">
<input type="file" name="image" id="aaa" />
</form>
java后台
// 封装上传文件域的属性
private File image;
// 封装上传文件类型的属性
private String imageContentType;
// 封装上传文件名的属性
private String imageFileName;
// 接受依赖注入的属性
private String savePath;
//图片上传方法
public void uploadPic(){
FileOutputStream fos = null;
FileInputStream fis = null;
if (null != image) {
try {
// 建立文件上传流
fis = new FileInputStream(image);
//获得项目路径
ServletContext application = session.getServletContext();
String serverRealPath = application.getRealPath("") ;
//获得当前时间
String sDatePath = sDatePath = DateUtil.format(new Date(), "yyyy/MM/dd");
//定义大中小图上传路径
String dir = serverRealPath+Constant.uploadUserUrl+"/"+sDatePath;
String dirMedium = serverRealPath+Constant.mediumUserUrl+"/"+sDatePath;
String dirSmall = serverRealPath+Constant.smallUserUrl+"/"+sDatePath;
// 判断文件夹是否存在,如果不存在就创建
//System.out.println("dir=="+dir);
findFolderIsExit(dir);
//System.out.println("dirMedium=="+dirMedium);
findFolderIsExit(dirMedium);
//System.out.println("dirSmall=="+dirSmall);
findFolderIsExit(dirSmall);
String[] data = imageFileName().split("\\.");
String houzhui = data[data.length - 1];
//文件新名称
String fileName = CommonUtil.getExchangeCode() + "." + houzhui;
// String fileName = imageFileName;
File uploadFile = new File(dir, fileName);
// 建立文件输出流
fos = new FileOutputStream(uploadFile);
byte[] buffer = new byte[1024];
int len = 0;
while ((len = fis.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
}catch (Exception e) {
System.out.println("文件上传失败");
e.printStackTrace();
} finally {
close(fos, fis);
}
}
}
//判断文件夹是否存在,如果不存在则创建文件夹
public static void findFolderIsExit(String path){
File file = new File(path);
if (!file.exists()) {
file.mkdirs();
}
}
/**
* 兑换编号
* 规则:日期+四位随机数
* 20130413+1234
* @return
*/
public static String getExchangeCode(){
Date date = new Date();
SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
String da = format.format(date);
Set<Integer> set = GetRandomNumber();
// 使用迭代器
Iterator<Integer> iterator = set.iterator();
// 临时记录数据
String temp = "";
while (iterator.hasNext()) {
temp += iterator.next();
}
return da+temp;
}