单个图片上传

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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值