注册页面头像上传的实现(javaweb相关)

注册页面头像上传的实现:

1. 注册页面:register.jsp

两种方式实现图片上传:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>register</title>
</head>
<script type="text/javascript" src="jquery-3.3.1.min.js"></script>
<style type="text/css">
body{
	margin-left:700px;
	margin-top:100px;
} 
table{
	width:500px;
	height:320px;
	border:1px solid #009999;
}
table tr{
	border:1px solid #009999;
}
table tr td{
	border:1px solid #009999;
	text-align:left;
}
</style>
<script type="text/javascript">
	/* var xhr;
//1.创建xmlhttprequest(xhr)对象
	function checkuser(){
		
		try{
		xhr=new XMLHttpRequest();
		
		}catch(e){
			xhr=new ActiveXObject("Microsoft.XMLHTTP");
		}
		//alert(xhr);
	//2.设置状态改变回调函数
	xhr.onreadystatechange=cb;
	var uname=document.getElementById("uname");
	//3.设置请求方式和路径
	//xhr.open("GET","CheckUserServlet?un="+uname.value);
	xhr.open("POST","CheckUserServlet");
	//如果是post请求必须加上请求头
	xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded")
	//4.发送请求
	xhr.send("un="+uname.value);
	}
	//5.处理响应内容
	function cb(){
		//完成响应
		if(xhr.readyState==4){
			//成功响应
			if(xhr.status==200){
				var resText=xhr.responseText;
				var msg=document.getElementById("msg");
				//alert(resText);
				if(resText=="t"){
					msg.style.color="red";
					msg.innerHTML="此用户名太受欢迎,请更换一个";
				}else{
					msg.style.color="green";
					msg.innerHTML="恭喜您:账号可以使用";
				}
			}
		}
		//alert(xhr.readyState);
	} */
	$(function(){
		$("#uname").blur(function(){
			$.post("CheckUserServlet",{un:this.value},function(resText){
				if(resText=="t"){
					$("#msg").css("color","red").html("此用户名太受欢迎,请更换一个");
				}else{
					$("#msg").css("color","green").html("恭喜您:账号可以使用");
				}
			})
		})
	})
</script>
<body >
<div id="all">
	<form action="RegServlet" method="post" enctype="multipart/form-data">
	<table>
	<tr>
	<td align="right" >创建用户名:</td>
	<td><input type="text" id="uname" name="username" onblur="checkuser()"/><span id="msg"></span></td>
	</tr>
	
	<tr>
	<td align="right">创建密码:</td>
	<td><input type="password" name="userpwd"/></td>
	</tr>
	
	<tr>
	<td align="right">注册邮箱:</td>
	<td><input type="text" name="mail"/></td>
	</tr>

	<tr>
	<td align="right">地址:</td>
	<td><input type="text" name="address"/></td>
	</tr>
	
	<tr>
	<td align="right">爱好:</td>
	<td><input type="text" name="hobby"/></td>
	</tr>
	
	<tr>
	<td align="right">头像:</td>
	<td><input type="file" name="photo"></td>
	</tr>
	
	<tr>
	<td align="right"><input type="submit" value="提交"/></td>
	<td align="right"><input type="reset" value="重置"/></td>
	</tr>
</table >
</form>
</div>
</body>
</html>

2.RegisterServlet:

package com.xintouyun.jweb.servlet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.xintouyun.jweb.entity.User;
import com.xintouyun.jweb.service.UserService;
import com.xintouyun.jweb.service.impl.UserServiceImpl;

public class RegServlet extends HttpServlet{
	public void doPost(HttpServletRequest request,HttpServletResponse response) throws IOException,ServletException{
		// Create a factory for disk-based file items
		DiskFileItemFactory factory = new DiskFileItemFactory();

		// Configure a repository (to ensure a secure temp location is used)
		ServletContext servletContext = this.getServletConfig().getServletContext();
		File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
		factory.setRepository(repository);

		// Create a new file upload handler
		ServletFileUpload upload = new ServletFileUpload(factory);

		// Parse the request
		try {
			User user=new User();
			List<FileItem> items = upload.parseRequest(request);
			for (FileItem item : items) {
				//如果是普通的form元素
				if(item.isFormField()) {
					String filename=item.getFieldName();
					String value=item.getString("utf-8");
					//System.out.println("普通form元素"+filename+":"+value);
					if(filename.equals("username")) {
						user.setUsername(value);
					}else if(filename.equals("userpwd")) {
						user.setUserpwd(value);
					}else if(filename.equals("mail")) {
						user.setEmail(value);
					}else if(filename.equals("address")) {
						user.setAddress(value);
					}else if(filename.equals("hobby")) {
						user.setHobby(value);
					}
				}else {
					String filename=item.getName();
					System.out.println("文件"+filename);
					//获取文件名的后缀
					String suffix=filename.substring(filename.lastIndexOf('.'));
					//为了防止上传到服务器中的文件重名,所以在上传的时候我们可以将文件进行自动生成前缀,只保留后缀,再拼接到一块的方法,来避免文件重名
					UUID uuid=UUID.randomUUID();
					String prefix=uuid.toString();
					//拼接后的文件名
					String savefilename=prefix+suffix;
					savefilename=savefilename.replace("-", "");
					//System.out.println("要保存的文件名为"+savefilename);
					String path=servletContext.getRealPath("/Images");
					user.setPhoto(savefilename);
					System.out.println("path"+path);
					InputStream is=item.getInputStream();
					OutputStream os=new FileOutputStream(new File(path+File.separator+savefilename));
					byte[] b=new byte[1024];
					int len;
					while((len=is.read(b))!=-1) {
						os.write(b, 0, len);
					}
					is.close();
					os.close();
				}
			}
			System.out.println("userpwd"+user.getUserpwd());
			UserService userservice=new UserServiceImpl();
			boolean result=userservice.saveUser(user);
			if(result) {
				//request.getRequestDispatcher("LoginPreServlet").forward(request, response);
				response.sendRedirect("LoginPreServlet");
			}else {
				response.sendRedirect("RegisterPreServlet");
			}
		} catch (FileUploadException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException,ServletException{
		this.doPost(request, response);
	}
}

3.配置xml文件

4.重启服务器,浏览器访问

展开阅读全文

没有更多推荐了,返回首页