用户编辑基本信息时的上传头像功能实现

一、编辑基本信息页面有“点击上传头像”和“提交”两个submit,需要设置不同的action
方法:在两个submit按钮的onclick事件处理过程中修改表单action属性,变更提交地址
具体实现代码:


	
	

二、jsp



三、action
将上传的头像保存至服务器中,并用输入输出流读出,数据库更新。

public class UploadHeadImgAction extends ActionSupport{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private File headImg;
	private String headImgContentType;
	private String headImgFileName;
	private Individual individual;
	private FileOutputStream fos;
	private FileInputStream fis;
	
	public String execute() throws Exception{
		
		//保存至服务器
		if(headImg!=null) {
			String filePath=ServletActionContext.getServletContext().getRealPath("/upload/headImgs");
			String fileName=UUID.randomUUID().toString().replaceAll("-","")+headImgFileName.substring(headImgFileName.lastIndexOf("."));
			FileUtils.copyFile(headImg, new File(filePath,fileName));
			
			//读出图片
			fos = new FileOutputStream(filePath+"/"+fileName);
			fis = new FileInputStream(headImg);
			byte[] buffer=new byte[1024];
			int len=0;
			while((len=fis.read(buffer))!=-1) {
				fos.write(buffer, 0, len);
			}
			fos.close();
			fis.close();

			//将图片在服务器中的位置通过request传递给前端
			String img="upload/headImgs/"+fileName;
			request.setAttribute("img", img);

			//ids是IndividualDaoService的一个对象,是对数据库中individual表进行操作
			的,该处对individual表中的headurl进行更新,id为通过其他方法获取的,可根
			据自身情况获取
			ids.updateHeadUrl(id, (String)request.getAttribute("img"));
			System.out.println("headImgUrl updated.");
			return "success";
		}else {
			return "noneImg";
		}
	}
	
	public File getHeadImg() {
		return headImg;
	}
	public void setHeadImg(File headImg) {
		this.headImg = headImg;
	}
	public String getHeadImgContentType() {
		return headImgContentType;
	}
	public void setHeadImgContentType(String headImgContentType) {
		this.headImgContentType = headImgContentType;
	}
	public String getHeadImgFileName() {
		return headImgFileName;
	}
	public void setHeadImgFileName(String headImgFileName) {
		this.headImgFileName = headImgFileName;
	}
	public Individual getIndividual() {
		return individual;
	}
	public void setIndividual(Individual individual) {
		this.individual = individual;
	}
	
}

四、显示


这里写了一个判断数据库中是否存在headurl来显示头像或者默认头像


		


		

你可能感兴趣的:(struts)