文件上传的前端页面:
multiple表示支持一次上传多个文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>上传文件</title>
</head>
<body>
<form action="/getFiles" enctype="multipart/form-data" method="post">
<input type="file" name="file" id="file" multiple><br />
<button type="submit">上传</button>
</form>
</body>
</html>
上传单个文件的servlet代码:
@MultipartConfig该注解表示这个servlet支持文件上传
package servlet;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
@WebServlet("/upload")
//location中写的是默认指定上传的路径,如果要是下面不写路径,就默认上传到这个路径
@MultipartConfig(location="E:\\temp")
public class UploadServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//设置编码格式,防止乱码
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
//上传文件的逻辑
//对应html里面写的name
Part file = req.getPart("file");
//获取上传文件的名称
String fileName = file.getSubmittedFileName();
String name = fileName;
System.out.println("上传文件的名称:" + fileName);
//html中定义的name属性的值
System.out.println(file.getName());
String dir = "E:\\upload";
fileName = dir + File.separator + fileName;
File file1 = new File(fileName);
if(!file1.getParentFile().exists()){
file1.getParentFile().mkdirs();
}
System.out.println(fileName);
try {
file.write(fileName);
String downloadLink = "<a href=\"/download?file=" + name + "\">下载图片</a>";
resp.getWriter().write("<h3>上传成功</h3>" + downloadLink);
}catch (IOException e){
e.printStackTrace();
resp.getWriter().write("<h3>上传失败</h3>");
}
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
}
}
支持一次上传多个文件的servlet代码实例:
package servlet;
import utils.Constant;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.util.Collection;
@WebServlet("/uploadfiles")
@MultipartConfig
public class UploadFilesServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//设置编码格式
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
//获取要上传的多个文件
Collection<Part> parts = req.getParts();
String downloadLink = "";
String message = "";
for (Part part : parts) {
//获取文件类型
String type = part.getContentType();
//获取要上传的文件名
String name = part.getSubmittedFileName();
if(Constant.ALLOW_TYPES.contains(type)){
String fileName = Constant.UPLOAD_PATH + File.separator + name;
File file = new File(fileName);
if(!file.getParentFile().exists()){
//目标目录不存在就去创建
file.getParentFile().mkdirs();
}
part.write(fileName);
downloadLink = downloadLink + "<a href='http://127.0.0.1/download?file=" + name + "'>下载" + name.substring(0,name.lastIndexOf(".")) + "</a><br>";
message = message + "<p>" + name + "上传成功</p>";
}else {
message = message + "<p>" + name + "上传失败,文件格式不支持</p>";
}
}
String html = "<html><body>";
html += message;
html += "<p>下载地址:</p>";
html += downloadLink;
html += "</body></html>";
resp.getWriter().write(html);
}
}
展示文件列表:
package servlet;
import utils.Constant;
import utils.FileUtils;
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;
@WebServlet("/list")
public class FileListServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
File file = new File(Constant.UPLOAD_PATH);
File[] files = file.listFiles(f -> f.isFile());
resp.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
if(files != null && files.length > 0){
StringBuilder html = new StringBuilder("<table>");
html.append("<tr>").append("<th>序号</th>").append("<th>文件名</th>").append("<th>文件大小</th>").append("<th>修改时间</th><th>操作</th></tr>");
//遍历这个目录
for (int i = 1; i <= files.length; i++) {
File f = files[i - 1];
html.append("<td>").append(i).append("</td>");
html.append("<td>").append(f.getName()).append("</td>");
html.append("<td>").append(FileUtils.getSize(f.length())).append("</td>");
html.append("<td>").append(FileUtils.getTime(f.lastModified())).append("</td>");
String downloadLink = "/download?file=" + f.getName();
html.append("<td><a").append(" href=").append(downloadLink).append(">下载</a>").append("</td>").append("</tr>");
}
html.append("</table>");
resp.getWriter().write(html.toString());
}else {
resp.getWriter().write("<h3>服务端上传目录为空</h3>");
}
}
}
下载文件的前端页面文章来源:https://www.toymoban.com/news/detail-717228.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<a href="/download?file=2.jpg">下载</a>
</body>
</html>
下载文件的servlet:文章来源地址https://www.toymoban.com/news/detail-717228.html
package servlet;
import utils.Constant;
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.File;
import java.io.FileInputStream;
import java.io.IOException;
@WebServlet("/download")
public class DownLoadServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//告诉浏览器要响应的是二进制流
resp.setContentType("application/octet-stream");
//获取本次下载的文件名称
String file = req.getParameter("file");
//设置以附件的形式下载,指定下载的文件名是原来的文件名
resp.setHeader("content-disposition","attachment;filename=" + file);
//要下载的文件的完整路径
String path = Constant.UPLOAD_PATH + File.separator + file;
//先用输入流读进来
FileInputStream in = new FileInputStream(path);
//获取响应的输出流
ServletOutputStream out = resp.getOutputStream();
//将文件的内容写入到输出流
in.transferTo(out);
out.flush();
out.close();
in.close();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
}
}
到了这里,关于实现文件上传和下载的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!