文件上传
返回学生对象、输入流、输出流
考虑注册成功与否,先对上传的数据进行处理
修改数据库表
对学生和老师添加photo字段
修改实体类
修改User
加一个属性private String photo;
相应修改子类Student、Teacer
新建StudentRegisterData
public class StudentRegisterData {
private Student student;
private InputStream in;
private OutputStream out;
...
}
输出查看
直接用if-else判断
@WebServlet("/RegisterServlet")
public class RegisterServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
StudentRegisterData studentRegisterData = parseRequestForStudent(request);
System.out.println(studentRegisterData.getStudent());
System.out.println(studentRegisterData.getIn());
System.out.println(studentRegisterData.getOut());
}
public static StudentRegisterData parseRequestForStudent(HttpServletRequest request){
StudentRegisterData studentRegisterData = new StudentRegisterData();
Student student = new Student();
//创建文件上传工厂类的对象
DiskFileItemFactory factory = new DiskFileItemFactory();
//创建文件上传类的对象
ServletFileUpload upload = new ServletFileUpload(factory);
try {
//解析请求
List<FileItem> list = upload.parseRequest(request);
for (FileItem fileItem : list) {
if(fileItem.isFormField()){//文本数据
String name = fileItem.getFieldName();
String value = fileItem.getString("UTF-8");
if(name.equals("username")){
student.setUsername(value);
} else if (name.equals("password")) {
student.setPassword(value);
} else if (name.equals("name")) {
student.setName(value);
} else if (name.equals("sex")) {
student.setSex(value);
} else if (name.equals("age")) {
student.setAge(Integer.parseInt(value));
} else if (name.equals("hobbies")) {
String hobbies = student.getHobbies();
if (hobbies ==null ){
student.setHobbies(value);
}else {
hobbies = hobbies + "," +value;
student.setHobbies(hobbies);
}
}
}else{//二进制数据
//获取项目发布路径 -- D:\\apache-tomcat-8.0.49\\webapps\\Day23_upload_war_exploded\\upload
String realPath = request.getServletContext().getRealPath("upload");
//文件存储目录 -- D:\\apache-tomcat-8.0.49\\webapps\\Day23_upload_war_exploded\\upload\\毫秒数
String path = realPath + File.separator + student.getUsername();
File file = new File(path);
if(!file.exists()){
file.mkdirs();
}
String fileName = fileItem.getName();//获取文件名
path = path + File.separator + fileName;//拼接路径
InputStream in = fileItem.getInputStream();
FileOutputStream out = new FileOutputStream(path);
studentRegisterData.setIn(in);
studentRegisterData.setOut(out);
student.setPhoto(path);
}
}
} catch (FileUploadException e) {
throw new RuntimeException(e);
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
studentRegisterData.setStudent(student);
return studentRegisterData;
}
}
修改RegisterServlet
使用map,简化if-else语句
注意:使用到IOUtils.copy(srdIn,srdOut);需要导commons的jar包
IOUtils基于Apache Commons,是一个工具类,用于简化文件和流的操作
@WebServlet("/RegisterServlet")
public class RegisterServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//解析请求,将请求中的数据封装起来
StudentRegisterData studentRegisterData = parseRequestForStudent(request);
Student srdStudent = studentRegisterData.getStudent();
InputStream srdIn = studentRegisterData.getIn();
OutputStream srdOut = studentRegisterData.getOut();
//通过username查询数据库中的学生对象
Student student = null;
try {
student = DBUtils.commonQueryObj(Student.class, "select * from student where username=?", srdStudent.getUsername());
} catch (SQLException e) {
throw new RuntimeException(e);
}
if(student == null){//允许注册
//将数据插入到学生表中
try {
DBUtils.commonUpdate("insert into student(username,password,name,sex,age,hobbies,photo) values(?,?,?,?,?,?,?)",srdStudent.getUsername(),srdStudent.getPassword(),srdStudent.getName(),srdStudent.getSex(),srdStudent.getAge(), srdStudent.getHobbies(),srdStudent.getPhoto());
} catch (SQLException e) {
throw new RuntimeException(e);
}
//将头像存储到本地磁盘
IOUtils.copy(srdIn,srdOut);
srdIn.close();
srdOut.close();
//利用重定向跳转到登录页面
response.sendRedirect("login.jsp");
}else{//不允许注册
srdIn.close();
srdOut.close();
//利用重定向跳转到注册页面
response.sendRedirect("register.jsp");
}
}
//解析请求,获取数据封装到学生对象里
//注意:返回学生对象、输入流、输出流
public static StudentRegisterData parseRequestForStudent(HttpServletRequest request){
StudentRegisterData studentRegisterData = new StudentRegisterData();
//创建文件上传工厂类的对象
DiskFileItemFactory factory = new DiskFileItemFactory();
//创建文件上传类的对象
ServletFileUpload upload = new ServletFileUpload(factory);
HashMap<String, String> map = new HashMap<>();
try {
//解析请求
List<FileItem> list = upload.parseRequest(request);
for (FileItem fileItem : list) {
if(fileItem.isFormField()){//文本数据
String name = fileItem.getFieldName();
String value = fileItem.getString("UTF-8");
String v = map.get(name);
if(v == null){//说明是第一次添加
map.put(name,value);
}else{//不是第一次添加就需要拼接(多选框的情况)
map.put(name,v + "," + value);
}
}else{//二进制数据
//获取项目发布路径 -- D:\\apache-tomcat-8.0.49\\webapps\\Day23_upload_war_exploded\\upload
String realPath = request.getServletContext().getRealPath("upload");
//文件存储目录 -- D:\\apache-tomcat-8.0.49\\webapps\\Day23_upload_war_exploded\\upload\\用户名
String path = realPath + File.separator + map.get("username");
File file = new File(path);
if(!file.exists()){
file.mkdirs();
}
String fileName = fileItem.getName();//获取文件名
//D:\\apache-tomcat-8.0.49\\webapps\\Day23_upload_war_exploded\\upload\\用户名\\tx01.jpg
path = path + File.separator + fileName;//拼接路径
InputStream in = fileItem.getInputStream();
FileOutputStream out = new FileOutputStream(path);
studentRegisterData.setIn(in);
studentRegisterData.setOut(out);
map.put("photo","upload" + File.separator + map.get("username") + File.separator + fileName);
}
}
} catch (FileUploadException e) {
throw new RuntimeException(e);
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
Set<Map.Entry<String, String>> entries = map.entrySet();
for (Map.Entry<String, String> entry : entries) {
System.out.println(entry);
}
Student student = new Student();
try {
//将map中的数据映射到实体类对象中
BeanUtils.populate(student,map);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
}
studentRegisterData.setStudent(student);
return studentRegisterData;
}
}
文件下载
下载页面
注意:浏览器能够识别的文件会展示,不能够识别的文件就下载
<body>
<%-- <a href="download/大理.jpg">下载图片</a>--%>
<a href="DownloadServlet">下载图片</a>
<a href="download/BMI资源.zip">下载压缩文件</a>
</body>
直接超链接情况
DownloadServlet处理
新建DownloadServlet
这里没有导commons的jar包,直接用IO流拷贝
@WebServlet("/DownloadServlet")
public class DownloadServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获取需要下载文件的路径
String realPath = request.getServletContext().getRealPath("download\\大理.jpg");
//截取出文件名
String fileName = realPath.substring(realPath.lastIndexOf("\\") + 1);
//设置编码格式
fileName = URLEncoder.encode(fileName,"UTF-8");
//设置响应头信息 -- 告诉浏览器该文件是以附件的形式下载
response.setHeader("Content-disposition", "attachment;fileName="+fileName);
//通过IO流向浏览器传输文件数据
FileInputStream in = new FileInputStream(realPath);
ServletOutputStream out = response.getOutputStream();
byte[] bs = new byte[1024];
int len;
while((len = in.read(bs)) != -1){
out.write(bs,0,len);
}
in.close();
out.close();
}
}