文件的上传和下载
这个星期学习了蛮多东西,我准备吧简单写一个文件的上传和下载.
<%--
Created by IntelliJ IDEA.
User: liqiuyang
Date: 2020/8/26
Time: 9:03
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=GB2312" language="java" %>
<html>
<head>
<title></title>
<meta charset="GB2312">
</head>
<body>
<form action="upload" enctype="multipart/form-data" method="post">
单个文件上传:<input type="file" name="myFile"><br>
username:<input type="text" name="myFile"><br>
<input type="submit" value="上传">
</form>
<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>
</body>
</html>
<%--
Created by IntelliJ IDEA.
User: liqiuyang
Date: 2020/8/26
Time: 10:37
To change this template use File | Settings | File Templates.
--%>
<%@ 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;
}
img{
width: 250px;
height: 250px;
}
p{
width:250px;
height: 20px;
}
p a{
width:250px;
height: 20px;
line-height: 20px;
margin-left: 40%;
}
</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">
<%--在jsp中获取容器中的目录位置
req.getServletContext().getPath()--%>
<img src="${pageContext.servletContext.contextPath}/upload/${f.getName()}">
<p>
${f.getName().substring(36)}
<br>
<%--向servlet提交完整的文件名--%>
<a href="down?fileName=${f.getName()}">下载</a>
</p>
</div>
</c:if>
</c:forEach>
</body>
</html>
package com.softeem.file.update;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.stream.events.EndDocument;
import java.io.*;
import java.net.URLEncoder;
/**
* @Author liqiuyang 2020/8/26 11:37
*/
@WebServlet("/down")
public class DownLoadServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String fileName = req.getParameter("fileName");
System.out.println(fileName);
//设置相应头,要求客户端浏览器激活下载功能
//mime:content-disposition
resp.setHeader("content-disposition","attachment;fileName="+ URLEncoder.encode(fileName,"utf-8"));
//io操作
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);
}
input.close();
out.close();
}
}
package com.softeem.file.update;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.UUID;
@WebServlet("/upload")
@MultipartConfig //该servlet可以处理二进制数据
public class FileUploadServlet extends javax.servlet.http.HttpServlet {
protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
//直接通过request对象获取文件对象
Part part = request.getPart("myFile");
Collection<Part> parts = request.getParts();
if(parts.size()==1) {
//获取提交的文件名
String fileName = part.getSubmittedFileName();
String header = part.getHeader("content-disposition");
System.out.println(header);
//获取提交的文件大小
long size = part.getSize();
//获取提交的文件类型
String type = part.getContentType();
System.out.println(fileName);
System.out.println(size);
//保存改文件
//如果访问容器中的目录
String path = request.getServletContext().getRealPath("upload");
System.out.println(path);
//设置文件名,防止文件覆盖
String filePath = path + File.separator + UUID.randomUUID() + fileName;
part.write(filePath);
}else{
parts.forEach(p->{
String path = request.getServletContext().getRealPath("upload");
String fileName = p.getSubmittedFileName();
try {
p.write(path+File.separator+UUID.randomUUID()+fileName);
} catch (IOException e) {
e.printStackTrace();
}
});
}
//控制器
response.sendRedirect("/getFiles");
}
}
package com.softeem.file.update;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
/**
* @Author liqiuyang 2020/8/26 10:45
*/
@WebServlet("/getFiles")
public class GetFiles extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
File f = new File(req.getServletContext().getRealPath("upload"));
//获取upload下所有文件
File[] files = f.listFiles();
req.setAttribute("files",files);
req.getRequestDispatcher("download.jsp").forward(req,resp);
}
}