目录
1 文件上传
1.1 实现效果
用户选择文件后,点击提交,文件以同一个名字可以存在工作目录
1.2 实现步骤
- 判断提交的数据是否为文件类型(ServletFileUpload.isMultipartContent(request))
- 创建一个文件解析器(ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);)
- 解析request到FileItem类型的list中(servletFileUpload.parse(request))
- 判断list中的是否为文件类型(fileItem.isFormField())
- 建一个存放文件的文件夹(在工作目录下)
- 获取文件的名字,和文件夹组成完成的路径
- 将解析到的内容(fileItem)输出到该文件(完整路径)
1.3 实现代码
前端:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<!-- 指定了base标签 -->
<base href="<%=request.getContextPath()+"/"%>>">
<style type="text/css">
input[type="submit"] {
outline: none;
border-radius: 5px;
cursor: pointer;
background-color: #31B0D5;
border: none;
width: 70px;
height: 35px;
font-size: 20px;
}
img {
border-radius: 50%;
}
form {
position: relative;
width: 200px;
height: 200px;
}
input[type="file"] {
position: absolute;
left: 0;
top: 0;
height: 200px;
opacity: 0;
cursor: pointer;
}
</style>
<script type="text/javascript">
function prev(event) {
//获取展示图片的区域
var img = document.getElementById("prevView");
//获取文件对象
var file = event.files[0];
//获取文件阅读器: Js的一个类,直接使用即可
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function () {
//给img的src设置图片url
img.setAttribute("src", this.result);
}
}
</script>
</head>
<body>
<!-- 表单的enctype属性要设置为multipart/form-data
enctype="multipart/form-data" 表示提交的数据是多个部分构造,有文件和文本
-->
<form action="UploadServlet" method="post" enctype="multipart/form-data">
图: <img src="2.jpg" alt="" width="200" height="200" id="prevView">
<input type="file" name="pic" id="" value="" onchange="prev(this)"/>
家居名: <input type="text" name="name"><br/>
<input type="submit" value="上传"/>
</form>
</body>
</html>
后端:
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;
public class UploadServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest requst, HttpServletResponse response) throws ServletException, IOException {
// System.out.println("通道打通");
if (ServletFileUpload.isMultipartContent(requst)) {
DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
servletFileUpload.setHeaderEncoding("utf-8");
try {
List<FileItem> lists = servletFileUpload.parseRequest(requst);
for(FileItem fileItem: lists){
if(fileItem.isFormField()){
String string = fileItem.getString("utf-8");
System.out.println("该文本的名字是"+string);
}else {
String name = fileItem.getName();
String upfile="/uploadfile/";
String realPath = requst.getServletContext().getRealPath(upfile);
File filedictory = new File(realPath);
if(!filedictory.exists()){
filedictory.mkdirs();
}
String fileFullPath=realPath+name;
fileItem.write(new File(fileFullPath));
response.setContentType("text/html;charset=utf-8");
response.getWriter().write("<h1>上传成功<h1/>");
}
}
} catch (Exception e) {
e.printStackTrace();
}
}else {
System.out.println("不是文件表单");
}
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req,resp);
}
}
2 文件下载
2.1 实现效果
2.2 实现步骤
- 准备好文件存储的目录
- 获得请求的文件name
- 获得文件存储文件夹+name完整路径
- setContentType和Content-Disposition
- 获得指定文件的输入流和response的输出流
- 使用IO的copy(),将文件输出
2.3 实现代码
前端:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>文件下载</title>
<base href="<%=request.getContextPath()+"/"%>>">
</head>
<body>
<h1>文件下载</h1>
<a href="downLoad?name=1.jpg">点击下载小狗图片</a><br/><br/>
<a href="downLoad?name=1.pdf">点击下载笔记.pdf</a><br/><br/>
</body>
</html>
后端:
import org.apache.commons.io.IOUtils;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
public class DownLoadServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("打通");
request.setCharacterEncoding("utf-8");
String name = request.getParameter("name");
String downLoadPath="/download/";
String downFullPath=downLoadPath+name;
String mimeType = request.getServletContext().getMimeType(downFullPath);
response.setContentType(mimeType);
response.setHeader("Content-Disposition", "attachment; filename=" +
URLEncoder.encode(name, "UTF-8"));
InputStream resourceAsStream = request.getServletContext().getResourceAsStream(downFullPath);
ServletOutputStream outputStream = response.getOutputStream();
IOUtils.copy(resourceAsStream,outputStream);
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
}