web 中保存头像功能

在Java web开发中,上传头像的开发主要分两个步骤

1、获取头像(file,contentType,filename)
2、保存头像
2.1、保存头像到指定的文件目录中
2.2、设置用户头像路径



	private File headImg;
	private String headImgContentType;
	private String headImgFileName;
	public File getHeadImg() {
		return headImg;
		}
		public void setHeadImg(File headImg) {
			this.headImg = headImg;
	}
	public String getContenType() {
	return contenType;
	}
	public void setContenType(String contenType) {
	this.contenType = contenType;
	}
	public String getHeadImgFileName() {
	return headImgFileName;
	}
	public void setHeadImgFileName(String headImgFileName) {
	this.headImgFileName = headImgFileName;
	}	//处理头像
	if(headImg != null){
	//1、保存头像到upload/user
	//获取保存路径的绝对地址
	String filePath = ServletActionContext.getServletContext().getRealPath("upload/user");
		//防止用户上传文件名为中文,或重复,自动设置上传图片后的文件名且后缀为文件格式
	String fileName = UUID.randomUUID().toString().replaceAll("-", "") + headImgFileName.substring(headImgFileName.lastIndexOf("."));
		//复制文件
		FileUtils.copyFile(headImg, new File(filePath, fileName));
					
		//2、设置用户头像路径
		user.setHeadImg("user/" + fileName);

 
 


猜你喜欢

转载自blog.csdn.net/qq_16651845/article/details/50954105