上传文件,form表单必须设置enctype="multipart/form-data" method必须为post
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
用户上传文件
Servlet3.0之前的版本需要引入:commons-fileupload、commons-io
package space.jokerplus.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 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 space.jokerplus.entity.User;
public class UserUploadServilet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 不包含上传文件直接返回
if (!ServletFileUpload.isMultipartContent(request)) {
return;
}
// 定义输入,输出流对象
OutputStream outputStream = null;
InputStream inputStream = null;
try {
// 获取登录用户
User user = (User) request.getSession().getAttribute("user");
// 1.创建fileFactory对象
DiskFileItemFactory fileFactory = new DiskFileItemFactory();
// 2.创建ServletFileUpload对象
ServletFileUpload fileUpload = new ServletFileUpload(fileFactory);
// 3.解析上传内容
List parseRequest = fileUpload.parseRequest(request);
// 4.遍历解析对象
for (FileItem fileItem : parseRequest) {
// 文件域的处理
if (!fileItem.isFormField()) {
// 4.1创建上传的文件夹,把上传的文件放到WEB-INF的upload下
// getRealPath(path) 获取服务器的真实地址,然后跟上path
// 如: D:\Program Files
// (x86)\apache-tomcat-7.0.81\webapps\FileOperateDemo\WEB-INF\\upload
// 最终上传的文件都将保存到该目录下
String uploadDir = request.getServletContext().getRealPath("/WEB-INF/upload");
// 如果文件夹不存在,创建文件夹
File uploadDirFile = new File(uploadDir);
if (!uploadDirFile.exists())
uploadDirFile.mkdir();
// System.out.println("上传文件夹位置: " + uploadDirFile.getPath());
// 4.2获取上传的全路径文件名
String fullFileName = fileItem.getName();
// 通过字符串截取来获得文件名
String fileName = fullFileName.substring(fullFileName.lastIndexOf("\\") + 1);
// 用户需要先登录,然后根据用户id生成文件夹
// 一个用户一个文件夹,防止不同用户之间的文件冲突
// 4.3创建当前用户上传使用的文件夹
File personalDir = new File(uploadDir, user.getId());
if (!personalDir.exists())
personalDir.mkdir();
// 获取输入流
inputStream = fileItem.getInputStream();
// 缓冲区
byte[] buffer = new byte[255 * 255];
int len = 0;
// 输出流
outputStream = new FileOutputStream(personalDir.getPath() + "\\" + fileName);
// 文件复制固定代码
while (-1 != (len = inputStream.read(buffer))) {
// 写出文件
outputStream.write(buffer, 0, len);
}
// 4.4保存用户上传的文件
user.addFile(fileName);
// 4.5上传完成后,跳转页面
// 重定向页面会改变url,需要全路径
response.sendRedirect(request.getServletContext().getContextPath() + "/download.jsp");
}
}
} catch (FileUploadException e) {
e.printStackTrace();
} finally {
// 关闭流
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
<%@page import="space.jokerplus.entity.User"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
下载文件
${file }
注意:tomcat8之前的编码默认为ISO-8859-1,需要设置编码方式
找到tomcat目录下的/conf/server.xml,找到
修完完毕后为:
package space.jokerplus.servlet;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import space.jokerplus.entity.User;
public class DownloadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 定义输入,输出流对象
OutputStream outputStream = null;
InputStream inputStream = null;
try {
// 设置请求和响应编码
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
//下载是通过超链接请求该Servlet(get请求),链接包含文件名
String filename = request.getParameter("filename");
// 获取保存文件的真实路径
String realPath = request.getServletContext().getRealPath("/WEB-INF/upload");
//获取登录用户,上传文件时根据用户id来为每个用户创建不同的文件夹
User user = (User) request.getSession().getAttribute("user");
String personalPath = user.getId();
// 设置浏览器接收文件类型
response.setContentType("image/jpeg");
// 下载文件的请求头,下载请求,必须设置
response.setHeader("Content-Disposition", "attachment; filename=" + filename);
// 文件输出流
outputStream = response.getOutputStream();
//拼接文件的真实地址
String filePath = realPath + "\\" + personalPath + "\\" + filename;
//获取文件的输入流
inputStream = new FileInputStream(new File(filePath));
//读取内容长度
int len = 0;
// 创建数据缓冲区
byte[] buffer = new byte[1024];
// 将FileInputStream流写入到buffer缓冲区
while ((len = inputStream.read(buffer)) != -1) {
// 使用OutputStream将缓冲区的数据输出到客户端浏览器
outputStream.write(buffer, 0, len);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 关闭资源
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
}
文件下载出现弹框需要设置响应头:"Content-Disposition : attachment; filename=文件名" ,代码为:response.setHeader("Content-Disposition", "attachment; filename=" + filename);
通过Content-Type来设置文件类型,如:Content-Type : image/jpeg,代码为: response.setContentType("image/jpeg");
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
登录
package space.jokerplus.servlet;
import java.io.IOException;
import java.util.UUID;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import space.jokerplus.entity.User;
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//接收用户名密码
String username = request.getParameter("username");
String password = request.getParameter("password");
//用户名,密码为null抛出异常
if("".equals(username) || null == username) {
throw new RuntimeException("用户名不能为null");
}
if("".equals(password) || null == password) {
throw new RuntimeException("密码不能为null");
}
//封装对象
User user = new User();
user.setUsername(username);
user.setPassword(password);
//没有连接数据库,使用UUID类生成随机字符串作为id
String id = UUID.randomUUID().toString();
user.setId(id);
//用户登录,保存信息
request.getSession().setAttribute("user", user);
//重定向页面会改变url,需要全路径
response.sendRedirect(request.getServletContext().getContextPath() + "/userupload.jsp");
}
}