掌握Servlet的HttpServletRequest对文件上传的支持;
能够理解文件上传的原理,掌握文件上传与下载的步骤
uploadHttpOne.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
<title>HttpServletResquest对文件上传的支持</title>
<meta charset="UTF-8">
</head>
<body>
<form action="uploadHttpOneServlst" method="post" enctype="multipart/form-data">
<table>
<tr>
<td>文件描述:</td>
<td><input type="text" name="filediscription"></td>
</tr>
<tr>
<td>请选择文件:</td>
<td><input type="file" name="resPath"></td>
</tr>
<tr>
<td align="right"><input type="reset" value="重填"></td>
<td><input type="submit" value="上传"></td>
</tr>
</table>
</form>
</body>
</html>
UploadHttpOneServlst.java
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;
import java.io.PrintWriter;
@MultipartConfig(maxFileSize = 10 * 1024 * 1024)
@WebServlet("/uploadHttpOneServlst")
public class UploadHttpOneServlst extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
request.setCharacterEncoding("UTF-8");
Part part = request.getPart("resPath");
String filediscription = request.getParameter("filediscription");
out.println("输入的文件描述:" + filediscription + "
");
File uploadFileDir = new File(getServletContext().getRealPath("/uploadFiles"));
if (!uploadFileDir.exists()) {
uploadFileDir.mkdir();
}
String oldName = MyUtil.getFileName(part);
out.println("上传文件的原始名:" + oldName + "
");
out.println("上传文件的大小:" + part.getSize() + "
");
if (oldName != null) {
part.write(uploadFileDir + File.separator + oldName);
}
out.println("文件上传到:" + uploadFileDir + File.separator + oldName + "
");
}
}
MyUtil.java
package servlet;
import javax.servlet.http.Part;
public class MyUtil {
public static String getFileName(Part part) {
if (part == null)
return null;
String fileName = part.getHeader("content-disposition");
if (fileName.lastIndexOf("=") + 2 == fileName.length() - 1)
return null;
return fileName.substring(fileName.lastIndexOf("=") + 2, fileName.length() - 1);
}
}
运行结果:
UploadHttpMultiServlst.java
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;
import java.io.PrintWriter;
import java.util.Collection;
@MultipartConfig
@WebServlet("/uploadHttpMultiServlst")
public class UploadHttpMultiServlst extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
request.setCharacterEncoding("UTF-8");
String filediscription1 = request.getParameter("filediscription1");
out.println("输入的文件1描述:" + filediscription1 + "
");
String filediscription2 = request.getParameter("filediscription2");
out.println("输入的文件2描述:" + filediscription2 + "
");
File uploadFileDir = new File(getServletContext().getRealPath("/uploadFiles"));
if (!uploadFileDir.exists()) {
uploadFileDir.mkdir();
}
Collection<Part> parts = request.getParts();
for (Part part : parts) {
if (part == null || !part.getName().contains("resPat")) {
continue;
}
String oldName = MyUtil.getFileName(part);
out.println("上传文件的原始名:" + oldName + "
");
out.println("上传文件的大小:" + part.getSize() + "
");
if (oldName != null) {
part.write(uploadFileDir + File.separator + oldName);
}
out.println("文件上传到:" + uploadFileDir + File.separator + oldName + "
");
}
}
}
MyUtil.java
package servlet;
import javax.servlet.http.Part;
public class MyUtil {
public static String getFileName(Part part) {
if (part == null)
return null;
String fileName = part.getHeader("content-disposition");
if (fileName.lastIndexOf("=") + 2 == fileName.length() - 1)
return null;
return fileName.substring(fileName.lastIndexOf("=") + 2, fileName.length() - 1);
}
}
UploadHttpMultiServlst.jsp
<%@ page contentType="text/html;charset=UTF-8"
language="java" pageEncoding="utf-8" %>
<!DOCTYPE html>
<html>
<head>
<title>HttpServletResquest对文件上传的支持</title>
<meta charset="UTF-8">
</head>
<body>
<form action="uploadHttpMultiServlst" method="post" enctype="multipart/form-data">
<table>
<tr>
<td>文件1描述:</td>
<td><input type="text" name="filediscription1"></td>
</tr>
<tr>
<td>请选择文件1:</td>
<td><input type="file" name="resPath1"></td>
</tr>
<tr>
<td>文件2描述:</td>
<td><input type="text" name="filediscription2"></td>
</tr>
<tr>
<td>请选择文件2:</td>
<td><input type="file" name="resPath2"></td>
</tr>
<tr>
<td align="right"><input type="reset" value="重填"></td>
<td><input type="submit" value="上传"></td>
</tr>
</table>
</form>
</body>
</html>
运行结果:
对多文件上传实例文件大小进行限定!
仅仅在UploadHttpMultiServlst.Java中加上限制条件——@MultipartConfig(maxFileSize = 10 * 1024 * 1024)//设置上传文件的最大值为10MB,其他代码不用变!
UploadHttpMultiServlst.Java
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;
import java.io.PrintWriter;
import java.util.Collection;
@MultipartConfig(maxFileSize = 10 * 1024 * 1024)//设置上传文件的最大值为10MB
@WebServlet("/uploadHttpMultiServlst")
public class UploadHttpMultiServlst extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
request.setCharacterEncoding("UTF-8");
String filediscription1 = request.getParameter("filediscription1");
out.println("输入的文件1描述:" + filediscription1 + "
");
String filediscription2 = request.getParameter("filediscription2");
out.println("输入的文件2描述:" + filediscription2 + "
");
File uploadFileDir = new File(getServletContext().getRealPath("/uploadFiles"));
if (!uploadFileDir.exists()) {
uploadFileDir.mkdir();
}
Collection<Part> parts = request.getParts();
for (Part part : parts) {
if (part == null || !part.getName().contains("resPat")) {
continue;
}
String oldName = MyUtil.getFileName(part);
out.println("上传文件的原始名:" + oldName + "
");
out.println("上传文件的大小:" + part.getSize() + "
");
if (oldName != null) {
part.write(uploadFileDir + File.separator + oldName);
}
out.println("文件上传到:" + uploadFileDir + File.separator + oldName + "
");
}
}
}
运行结果:
当其中一个文件大小大于10MB时,无法上传文件数据:
当文件小于10MB时,能够正常上传:
实验代码和运行结果如下:
导包:
ShowDownServlet.java
package servlet;
import javax.servlet.RequestDispatcher;
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("/showDownServlet")
public class ShowDownServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//指定从服务器uploadFiles目录中下载文件
File downLoadFileDir = new File(getServletContext().getRealPath("/uploadFiles"));
//获得目录中的文件
File[] list = downLoadFileDir.listFiles();
request.setAttribute("fileList", list);
RequestDispatcher dis = request.getRequestDispatcher("showInfo.jsp");
dis.forward(request, response);
}
}
MyUtil.java
package servlet;
import javax.servlet.http.Part;
import java.io.UnsupportedEncodingException;
public class MyUtil {
public static String getFileName(Part part) {
if (part == null)
return null;
String fileName = part.getHeader("content-disposition");
if (fileName.lastIndexOf("=") + 2 == fileName.length() - 1)
return null;
return fileName.substring(fileName.lastIndexOf("=") + 2, fileName.length() - 1);
}
//处理乱码问题
public static String toUTF8String(String str) {
StringBuffer sb = new StringBuffer();
int len = str.length();
for (int i = 0; i < len; i++) {
char c = str.charAt(i);
if (c >= 0 && c <= 255) {
sb.append(c);
} else {
byte b[];
try {
b = Character.toString(c).getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
b = null;
}
for (int j = 0; j < b.length; j++) {
int k = b[j];
if (k < 0) {
k &= 255;
}
sb.append("&" + Integer.toHexString(k).toUpperCase());
}
}
}
return sb.toString();
}
}
DownloadServlet.java
package 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.File;
import java.io.FileInputStream;
import java.io.IOException;
@WebServlet("/downloadServlet")
public class DownloadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
File downLoadFileDir = new File(getServletContext().getRealPath("/uploadFiles"));
String aFileName = null;
FileInputStream in = null;
ServletOutputStream out = null;
try {
aFileName = request.getParameter("resPath");
response.setHeader("Content-Type", "application/x-msdownload");
response.setHeader("Content-Dissposition", "attachment;filename=" + MyUtil.toUTF8String(aFileName));
in = new FileInputStream(downLoadFileDir + File.separator + aFileName);
out = response.getOutputStream();
out.flush();
int aRead = 0;
byte b[] = new byte[1024];
while ((aRead = in.read(b)) != -1 & in != null) {
out.write(b, 0, aRead);
}
out.flush();
in.close();
out.close();
} catch (Throwable e) {
e.printStackTrace();
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
}
showInfo.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="utf-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<title>显示下载文件</title>
<meta charset="UTF-8">
</head>
<body>
<form action="uploadHttpMultiServlst" method="post" enctype="multipart/form-data">
<table border="1">
<tr bgcolor="#90ee90">
<th>文件名称</th>
<th>下载课件</th>
</tr>
<c:forEach var="afile" items="${fileList}">
<tr>
<td>${afile.name}</td>
<td align="center"><a href="downloadServlet?resPath=${afile.name}"
style="text-decoration: yellow">下载</a></td>
</tr>
</c:forEach>
</table>
</form>
</body>
</html>
运行结果: