一.文件的上传:
- 使用form表单提交并上传文件。
注意:encType = “multipart/form-data”;表单的method必须是post ; input 的 file 必须有 name 。
<%@page import="com.EzerbelCN.servlets.TempUtils"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<% %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Welcome ! Pictures Here !</title>
<style type="text/css">
img{
width:200px;
height:120px;
}
.imgs{
float:left;
width:250px;
}
</style>
<%
application.setAttribute("ctp", request.getContextPath());
%>
</head>
<body>
<form action="${ctp}/upload" method="post" enctype="multipart/form-data">
用户名:<input type="text" name="username"/><br/>
头像:<input type="file" name="headerimg" accept="image/jpg,image/png"/><br/>
<input type="submit" value="提交"><br/>
</form>
<hr/>
<div>
<c:forEach items="<%=TempUtils.getPaths()%>" var="path">
<div class="imgs">
<img src="/2.FileUpload/${path}"></img><br/>
<!-- 不要在前面加 /-->
<a href="download?file=${path}">下载图片</a>
</div>
</c:forEach>
</div>
</body>
</html>
- 接受并处理post请求
借助commons-fileupload-1.3.1.jar、commons-io-2.2.jar可以快速实现对带有文件上传的表单解析。
package com.EzerbelCN.servlets;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.UUID;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;
public class UploadServlet extends HttpServlet {
private static final long serialVersionUID = -6724597434450649221L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 当前请求是否是一个多部件(文件上传)请求?
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if(isMultipart) {
// Create a factory for disk-based file items
DiskFileItemFactory factory = new DiskFileItemFactory();
// Configure a repository (to ensure a secure temp location is used)
ServletContext servletContext = this.getServletConfig().getServletContext();
File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
String realPath = servletContext.getRealPath("/pics");
File repo = new File(realPath);
factory.setRepository(repo);
System.out.println("pics realPath =============== " + realPath);
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
//一个FileItem代表一个表单(form)项的详细信息
try {
// Parse the request
List<FileItem> items = upload.parseRequest(request);
System.out.println("items.size == " + items.size());
for (FileItem fileItem : items) {
if(!fileItem.isFormField()) {
System.out.println("提交的表单 key = " + fileItem.getFieldName());
System.out.println("上传的文件名 = " + fileItem.getName());
// IE或Edge浏览器所get到的filename会带有路径,必须把路径去掉才行
String fname = fileItem.getName();
int lastIndexOf = fname.lastIndexOf("\\");
fname = fname.substring(lastIndexOf+1);
//加上UUID作为前缀防止重名
fname = UUID.randomUUID().toString().replace("-", "")+fname;
InputStream is = fileItem.getInputStream();
FileOutputStream os = new FileOutputStream(realPath + "\\" + fname);
//os.write(fileItem.get());
System.out.println("fname == " + fname);
System.out.println(realPath +"\\"+fname);
IOUtils.copy(is, os);
os.close();
is.close();
//存到一个类的静态成员List中用于后续下载使用
TempUtils.AddImg("pics/"+fname);
}else {
System.out.println("普通表单项: key = " + fileItem.getFieldName() + " value= " + fileItem.getString() );
}
}
} catch (FileUploadException e) {
e.printStackTrace();
}
}
request.getRequestDispatcher("/index.jsp").forward(request, response);
}
}
- 配置web.xml
<servlet>
<servlet-name>UploadServlet</servlet-name>
<servlet-class>com.EzerbelCN.servlets.UploadServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>UploadServlet</servlet-name>
<url-pattern>/upload</url-pattern>
</servlet-mapping>
- 测试
二.文件的下载
1) 处理下载请求
package com.EzerbelCN.servlets;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils;
public class DownloadServlet extends HttpServlet {
private static final long serialVersionUID = 8980356474131595540L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("Dooo Gettt");
String file = request.getParameter("file");
//1.servletContext用于获得真实路径
ServletContext servletContext = this.getServletConfig().getServletContext();
String realPath = servletContext.getRealPath(file);
//截掉前面的路径
int lastIndexOf = file.lastIndexOf("/");
String fname = file.substring(lastIndexOf+1);
//截掉前面的UUID
int UIDLen = UUID.randomUUID().toString().replace("-", "").length();
fname = fname.substring(UIDLen);
//转换编码格式防止中文乱码,UTF8 -> GBK -> ISO-8859-1
fname = new String(fname.getBytes("GBK"),"ISO-8859-1");
//告诉浏览器这是一个附件,需要下载,不能直接在浏览器显示
response.setHeader("Content-Disposition", "attachment;filename="+fname);
System.out.println("file == " + file);
System.out.println("fname == " + fname);
System.out.println("realPath == " + realPath);
//2.获得要下载的输入流
FileInputStream fis = new FileInputStream(realPath);
//3.获得输出流
ServletOutputStream sos = response.getOutputStream();
IOUtils.copy(fis, sos);
sos.close();
fis.close();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
- 配置web.xml
<servlet>
<servlet-name>DownloadServlet</servlet-name>
<servlet-class>com.EzerbelCN.servlets.DownloadServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DownloadServlet</servlet-name>
<url-pattern>/download</url-pattern>
</servlet-mapping>
- 下载测试