文件上传
上传文件对表单的要求(前端<form>)
1.请求方式为post method="post"
2.enctype="multipart/form-data"
3.使用 文件表单项上传文件
用户名:<input type="text" name="username">
文件:<input type="file" name="photo">
<input type="submit" value="提交">
对servlet限制
1.request.getParameter()方法不能再使用
即使用了也获取的是null
2.request.getInputStream()来获取所有消息体数据
使用第三方工具类,来解析请求体中的文件的数据
1.导入jar包
commons-fileupload.jar
commons-io.jar
2.创建解析器工厂
new DiskFileItemFactory();
3.获取解析器
new ServletFileUpload(diskFileItemFactory);
4.解析request对象 返回List<FileItem> (表单项对象集合)
servletFileUpload.parseRequest(request);
5.遍历集合 获取每一个表单项 获取数据
for(FileItem fileItem : list)
判断是否是普通表单项
boolean b = fileItem.isFormField();
获取表单项name名称
fileItem.getFieldName();
true 表示普通表单项
if("username".equals(fieldName))
获取表单项的值
String name = fileItem.getString();
false 表示文件表单项
getName();获取文件名
getSize();获取文件大小 单位字节
getContentType();获取文件类型
将文件写入硬盘
这个upload文件夹一开始判断一下,如果不存在,要用代码创建出来
File dir = new File(this.getServletContext().getRealPath("/upload"));
File file = new File(dir,name);
fileItem.write(file);
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
快速入门
@WebServlet(value = "/fileUpload", name = "FileUploadServlet")
public class FileUploadServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
List<FileItem> list = servletFileUpload.parseRequest(request);
String uname = null;
String upwd = null;
for (FileItem fileItem : list) {
boolean formField = fileItem.isFormField();
String fieldName = fileItem.getFieldName();
if (formField) {
if ("username".equals(fieldName)) {
uname = fileItem.getString("utf-8");
System.out.println(uname);
}
if ("password".equals(fieldName)) {
upwd = fileItem.getString("utf-8");
System.out.println(upwd);
}
} else {
String fileName = fileItem.getName();
fileName = System.currentTimeMillis() + "-" + fileName;
long size = fileItem.getSize();
String contentType = fileItem.getContentType();
File dir = new File(this.getServletContext().getRealPath("/uploadPhoto"));
if (!dir.exists()) {
dir.mkdirs();
}
File file = new File(dir, fileName);
fileItem.write(file);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
异步文件上传
AjaxUpload.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="utf-8" %>
<html>
<head>
<title>登录title>
<script src="js/jquery.js">script>
head>
<body>
<form id="addForm" action="${pageContext.request.contextPath}/login" method="post" enctype="multipart/form-data">
<input type="text" name="username" value="jack" />
<input type="password" name="password" value="123456" />
<input type="file" id="myPhoto" name="avatar" />
<input type="submit" value="确认">
form>
body>
<%--异步上传文件--%>
<script>
$("#myPhoto").blur(function () {
var data = new FormData($("#addForm")[0]);
$.ajax({
type: 'post',
url: '${pageContext.request.contextPath}/fileUpload',
cache: false,
processData: false,
contentType: false,
data: data,
dataType: 'json',
success: function (data) {
alert(data.msg);
},
error: function () {
alert("请求失败");
}
})
})
script>
html>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
FileUploadServlet.java
@WebServlet(value = "/fileUpload", name = "FileUploadServlet")
public class FileUploadServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
List<FileItem> list = servletFileUpload.parseRequest(request);
String uname = null;
String upwd = null;
for (FileItem fileItem : list) {
boolean formField = fileItem.isFormField();
String fieldName = fileItem.getFieldName();
if (formField) {
if ("username".equals(fieldName)) {
uname = fileItem.getString("utf-8");
System.out.println(uname);
}
if ("password".equals(fieldName)) {
upwd = fileItem.getString("utf-8");
System.out.println(upwd);
}
} else {
String fileName = fileItem.getName();
fileName = System.currentTimeMillis() + "-" + fileName;
long size = fileItem.getSize();
String contentType = fileItem.getContentType();
File dir = new File(this.getServletContext().getRealPath("/uploadPhoto"));
if (!dir.exists()) {
dir.mkdirs();
}
File file = new File(dir, fileName);
fileItem.write(file);
response.setContentType("text/json;charset=utf-8");
response.getWriter().write("{\"msg\":\"上传成功\",\"filename\":\" " + fileName + " \"}");
request.getSession().setAttribute("username", uname);
request.getSession().setAttribute("fileName", fileName);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
文件下载
服务器端保存到客户端
1.超链接直接指向目标资源下载
如果浏览器可以解析目标文件,则直接在浏览器中打开。
反之,则弹出下载提示框
超链接下载
2.通过Servlet实现下载
a.超链接指向servlet,传递目标资源的标识符
图片请求servlet
b.定义Servlet
获取文件名
request.getParameter("filename");
获取图片在服务器所在位置
request.getServletContext().getRealPath("");
new FileInputStream(realPath);
设置响应头
告诉浏览器 响应消息体数据打开方式 让浏览器打开下载框
response.setHeader("content-disposition", "attachment;filename=" + filename);
response.setHeader("content-type", this.getServletContext().getMimeType(filename));
响应回去
CopyUtils.copy(in,response.getOutputStream);
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
快速入门
downLoad.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Titletitle>
head>
<body>
<a href="${pageContext.request.contextPath}/upload/1.jpg">超链接下载a>
<br>
<a href="${pageContext.request.contextPath}/download?filename=2.jpg">图片请求servleta>
body>
html>
DownLoadServlet.java
@WebServlet(value = "/download", name = "DownLoadServlet")
public class DownLoadServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String filename = request.getParameter("filename");
String realPath = request.getServletContext().getRealPath("/WEB-INF/img/" + filename);
FileInputStream in = new FileInputStream(realPath);
response.setHeader("content-disposition", "attachment;filename=" + filename);
response.setHeader("content-type", this.getServletContext().getMimeType(filename));
CopyUtils.copy(in, response.getOutputStream());
in.close();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25