javaweb实现文件的上传与下载
前端页面设计
上传前端页面
这里我们只要一个简单的jsp页面,使用input实现,每一个页面元素必须设定一个name属性,这在之后的servlet必须要用到。
<%@ page contentType="text/html; charset=GB2312" language="java" %>
<html>
<head>
<title>Title</title>
<meta charset="GB2312">
</head>
<body>
<fieldset>
<form action="upload" enctype="multipart/form-data" method="post">
单个文件上传:<input type="file" name="myFile"><br>
<input type="submit" value="上传">
</form>
</fieldset>
<fieldset>
<form action="upload" enctype="multipart/form-data" method="post">
多个文件上传:<input type="file" name="myFile"><br>
<input type="file" name="myFile"><br>
<input type="submit" value="上传">
</form>
</fieldset>
</body>
</html>
下载前端页面
一个简单的下载端jsp界面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>Title</title>
<style>
.card{
width: 250px;
height: 250px;
float: left;
}
</style>
</head>
<body>
<c:set var="types" value="'jpg','jpeg','png'"></c:set>
<c:forEach var="f" items="${files}">
<c:if test="${f.getName().endsWith('jpg')}">
<div class="card">
<img src="${pageContext.servletContext.contextPath}/upload/${f.getName()}" width="150px" height="150px">
<p>
${f.getName().substring(36)}
<br>
<a href="down?fileName=${f.getName()}">下载</a>
</p>
</div>
</c:if>
</c:forEach>
</body>
</html>
上传下载功能实现
文件上传
创建一个类继承HttpServlei,重写doPost方法后,先通过request获取文件对象,之后可以根据需求获取文件名、文件大小、文件类型。
由于涉及到文件的传输,所以要为该Servlet添加上一个处理二进制数据的能力。这部分可以通过注释@MultipartConfig实现。主要使用Part
实现文件上传后,根据需求我们可以展开下载列表,这里我们可以重定向文件列表展开界面。
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Part part = req.getPart("myFile");
Collection<Part> parts = req.getParts();
if (parts.size() == 1) {
String fileName = part.getSubmittedFileName();
long size = part.getSize();
String type = part.getContentType();
System.out.println(fileName);
System.out.println(size);
String path = req.getServletContext().getRealPath("upload");
System.out.println(path);
String filePath = path + File.separator + UUID.randomUUID() + fileName;
part.write(filePath);
}else{
parts.forEach(p->{
String path = req.getServletContext().getRealPath("upload");
String fileName = p.getSubmittedFileName();
try {
p.write(path+File.separator+UUID.randomUUID()+fileName);
} catch (Exception e){
e.printStackTrace();
}
});
}
resp.sendRedirect("/javaweb05/getFiles");
}
文件列表
创建一个类继承HttpServlet,重写doget方法,获取所有的文件对象,再转发到文件下载界面
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
File f = new File(req.getServletContext().getRealPath("upload"));
File [] files = f.listFiles();
req.setAttribute("files",files);
req.getRequestDispatcher("download.jsp").forward(req,resp);
}
文件下载
这部分使用的是IO流操作,这部分要先寻找好源文件的路径。
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String fileName = req.getParameter("fileName");
System.out.println(fileName);
resp.setHeader("content-disposition","attachment;fileName="+ URLEncoder.encode(fileName,"utf-8"));
String path = req.getServletContext().getRealPath("upload")+ File.separator+fileName;
InputStream input = new FileInputStream(path);
OutputStream out = resp.getOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len=input.read(buffer)) != -1){
out.write(buffer);
}
out.close();
input.close();
}