文件上传
ps图像上传:通过浏览器客户端将图片上传到服务器的磁盘上
原理
所谓的文件上传就是服务器端通过request对象获取输入流,将浏览器端上传的数据读取出来,保存到服务器端
客户端:
1.请求方式必须是 post
2.需要使用组件< input type="file" name="file">
3.表单必须设置enctype="multipart/form-data"
服务器端:
通过request对象,获取InputStream, 可以将浏览器提交的所有数据读取到
学生管理系统
上传头像
以IO流为基础先输出
jsp
public static void method(HttpServletRequest request, HttpServletResponse response) throws IOException {
ServletInputStream in = request.getInputStream();
StringBuffer sb = new StringBuffer();
byte[] bs = new byte[1024];
int len;
while ((len = in.read(bs)) != -1){
sb.append(new String(bs,0,len));
}
System.out.println(sb.toString());
}
fileItem是一条一条的,根据不同的数据类型做不同的处理
修改register.jsp
jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>注册页面</h1>
<form action="RegisterServlet" method="post" enctype="multipart/form-data">
账号:<input type="text" name="username"/><br/>
密码:<input type="password" name="password"/><br/>
姓名:<input type="text" name="name"/><br/>
年龄:<input type="text" name="age"/><br/>
性别:
<input type="radio" name="sex" value="man" checked="checked"/>男
<input type="radio" name="sex" value="woman"/>女
<br/>
爱好:
<input type="checkbox" name="hobbies" value="football"/>足球
<input type="checkbox" name="hobbies" value="basketball"/>篮球
<input type="checkbox" name="hobbies" value="shop"/>购物
<br/>
上传头像:<input type="file" name="photo"/><br/>
<input type="submit" value="注册"/>
<input type="button" value="返回" οnclick="goWelcome()"/>
</form>
<script type="text/javascript">
function goWelcome(){
window.location = "welcome.html";
}
</script>
</body>
</html>
修改RegisterServlet
创建文件上传工厂类的对象
创建文件上传类的对象
解析请求
这里主要是二进制数据的处理,利用发布路径+时间解决文件名重复问题,并且不会改变原文件名
用 File.separator 来代替路径分隔符
java
@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 {
//创建文件上传工厂类的对象
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();
System.out.println("文本数据 -- " + name);
}else{//二进制数据
//获取项目发布路径 -- D:\\apache-tomcat-8.0.49\\webapps\\MyDay23_upload_war_exploded\\upload
String realPath = request.getServletContext().getRealPath("upload");
//文件存储目录 -- D:\\apache-tomcat-8.0.49\\webapps\\MyDay23_upload_war_exploded\\upload\\毫秒数
String path = realPath + File.separator + System.currentTimeMillis();
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);
IOUtils.copy(in,out);
in.close();
out.close();
}
}
} catch (FileUploadException e) {
throw new RuntimeException(e);
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
实现1
//处理二进制数据 -- 利用传统IO的方式拷贝到本地磁盘
public static void method01(HttpServletRequest request){
//创建文件上传工厂类的对象
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();
System.out.println("文本数据 -- " + name);
}else{//二进制数据
InputStream in = fileItem.getInputStream();
FileOutputStream out = new FileOutputStream("D:\\test\\xxx.jpg");
byte[] bs = new byte[1024];
int len;
while((len = in.read(bs)) != -1){
out.write(bs,0,len);
}
in.close();
out.close();
}
}
} catch (FileUploadException e) {
throw new RuntimeException(e);
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
实现2
//处理二进制数据 -- 利用IOUtils实现文件的拷贝
public static void method02(HttpServletRequest request){
//创建文件上传工厂类的对象
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();
System.out.println("文本数据 -- " + name);
}else{//二进制数据
InputStream in = fileItem.getInputStream();
FileOutputStream out = new FileOutputStream("D:\\test\\xxx.jpg");
IOUtils.copy(in,out);
in.close();
out.close();
}
}
} catch (FileUploadException e) {
throw new RuntimeException(e);
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
实现3
//处理二进制数据 -- 获取文件名存储文件
//问题:文件名重复,会覆盖
public static void method03(HttpServletRequest request){
//创建文件上传工厂类的对象
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();
System.out.println("文本数据 -- " + name);
}else{//二进制数据
String path = "D:\\test";//文件存储目录
String fileName = fileItem.getName();//获取文件名
path = path + File.separator + fileName;//拼接路径
InputStream in = fileItem.getInputStream();
FileOutputStream out = new FileOutputStream(path);
IOUtils.copy(in,out);
in.close();
out.close();
}
}
} catch (FileUploadException e) {
throw new RuntimeException(e);
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
实现4
//处理二进制数据 -- 利用UUID解决文件名重复的问题
//问题1:改变了原有的文件名
//问题2:代码的可移植性不高(指定了路径-D:\test)
public static void method04(HttpServletRequest request){
//创建文件上传工厂类的对象
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();
System.out.println("文本数据 -- " + name);
}else{//二进制数据
String path = "D:\\test";//文件存储目录
//获取随机的UUID对象(理解:随机UUID对象 = 系统参数+对象内存地址+算法)
UUID uuid = UUID.randomUUID();
String fileName = fileItem.getName();//获取文件名
fileName = uuid + fileName;//拼接文件名
path = path + File.separator + fileName;//拼接路径
InputStream in = fileItem.getInputStream();
FileOutputStream out = new FileOutputStream(path);
IOUtils.copy(in,out);
in.close();
out.close();
}
}
} catch (FileUploadException e) {
throw new RuntimeException(e);
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
实现5
//处理二进制数据 -- 利用发布路径+时间解决文件名重复问题,并且不会改变原文件名
public static void method05(HttpServletRequest request){
//创建文件上传工厂类的对象
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();
System.out.println("文本数据 -- " + name);
}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 + System.currentTimeMillis();
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);
IOUtils.copy(in,out);
in.close();
out.close();
}
}
} catch (FileUploadException e) {
throw new RuntimeException(e);
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}