文件的上传、下载(Servlet)
程序员文章站
2022-06-02 13:54:01
...
1.引入依赖
<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
2.编写上传类UploadServlet.java
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.*;
import java.util.List;
public class UploadServlet extends HttpServlet {
private static final int MEMORY_THRESHOLD = 1024 * 1024 * 3;
private static final int MAX_FILE_SIZE = 1024 * 1024 * 40;
private static final int MAX_REQUEST_SIZE = 1024 * 1024 * 50;
private static final String UPLOAD_DIRECTORY = "upload";
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
out.println("<html>");
out.println("<body>");
out.println("<h2>");
out.println("hi");
out.println("</h2>");
out.println("</body>");
out.println("</html>");
out.flush();
out.close();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
if (!ServletFileUpload.isMultipartContent(req)) {
PrintWriter out = resp.getWriter();
out.println("表单type错误,必须包含 enctype=multipart/form-data");
out.flush();
out.close();
}
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(MEMORY_THRESHOLD);
factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setFileSizeMax(MAX_FILE_SIZE);
upload.setSizeMax(MAX_REQUEST_SIZE);
upload.setHeaderEncoding("UTF-8");
String uploadPath = req.getServletContext().getRealPath("./") + File.separator + UPLOAD_DIRECTORY;
File uploadDir = new File(uploadPath);
if (!uploadDir.exists())
uploadDir.mkdir();
try {
List<FileItem> fileItems = upload.parseRequest(req);
if (fileItems == null || fileItems.size() == 0) {
req.setAttribute("message", "没有有效文件");
}
for (FileItem item : fileItems) {
if (!item.isFormField()) { // 判断表单是否是file类型(false为file)
String fileName = new File(item.getName()).getName();
String filePath = uploadPath + File.separator + fileName;
File storeFile = new File(filePath);
System.out.println(item.getString("gbk"));
FileOutputStream fout = new FileOutputStream(storeFile);
OutputStreamWriter oStreamWriter = new OutputStreamWriter(fout,"gbk");
oStreamWriter.append(item.getString("gbk"));
oStreamWriter.flush();
oStreamWriter.close();
req.setAttribute("message", "文件上传成功");
}
}
} catch (Exception e) {
req.setAttribute("message",
"错误信息: " + e.getMessage());
}
req.getServletContext().getRequestDispatcher("/message.jsp").forward(req, resp);
}
}
3.编写下载类DownloadServlet.java
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
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;
import java.net.URLEncoder;
public class DownloadServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 暂时写死了路径
File file = new File("E:\\workspace\\servlet-study\\target\\servlet-study\\upload\\girl.jpg");
if (!file.exists()) {
req.setAttribute("message", "下载文件不存在");
req.getServletContext().getRequestDispatcher("/message.jsp").forward(req, resp);
}
FileInputStream fis = new FileInputStream(file);
String filename = URLEncoder.encode(file.getName(),"utf-8"); //解决中文文件名下载后乱码的问题
byte[] b = new byte[fis.available()];
fis.read(b);
resp.setCharacterEncoding("UTF-8");
resp.setHeader("Content-Disposition", "attachment; filename=" + filename);
ServletOutputStream out = resp.getOutputStream();
out.write(b);
out.flush();
out.close();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doGet(req, resp);
}
}
3.编写上传页面(index.jsp)<%@page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>文件上传</title>
</head>
<body>
<h2>文件上传!</h2>
<form method="post" action="/uploadServlet" enctype="multipart/form-data">
选择一个文件
<input type="file" name="uploadFile">
<br/>
<br/>
<input type="submit" value="上传">
</form>
</body>
</html>
4.结果提示页面(message.jsp)
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" pageEncoding="UTF-8" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>文件上传结果</title>
</head>
<body>
<h2>${message}</h2>
</body>
</html>
5.web.xml
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>testServlet</servlet-name>
<servlet-class>com.fee.controller.TestServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>testServlet</servlet-name>
<url-pattern>/testServlet</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>uploadServlet</servlet-name>
<servlet-class>com.fee.controller.UploadServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>uploadServlet</servlet-name>
<url-pattern>/uploadServlet</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>downloadServlet</servlet-name>
<servlet-class>com.fee.controller.DownloadServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>downloadServlet</servlet-name>
<url-pattern>/downloadServlet</url-pattern>
</servlet-mapping>
</web-app>
6.上传结果及路径
上一篇: flash as3生成XML文件实现程序
下一篇: oracle union 用法讲解