JSP与Servlet文件上传和下载
程序员文章站
2022-06-02 13:54:07
...
JSP与Servlet文件上传和下载
下载较为简单先写下载
pom.xml的配置
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.3</version>
</dependency>
</dependencies>
导入jsp和servlet的依赖
Servlet内容:
package com.wen.servlet;
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.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;
public class DownLoadServlet extends HttpServlet {
//由于get或者post只是请求实现的不同的方式,可以相互调用,业务逻辑都一样;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String realPath = "D:\\upload\\2.jpg";
System.out.println("文件下载路径"+realPath);
String filename = realPath.substring(realPath.lastIndexOf("\\")+1);
/*
* 获取最后一个\分割的位置,+1就是文件名
* */
resp.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(filename,"utf-8"));
FileInputStream in = new FileInputStream(realPath);
int len = 0;
byte[] buffer = new byte[1024];
ServletOutputStream out = resp.getOutputStream();
while ((len = in.read(buffer))!=-1){
out.write(buffer,0,len);
}
out.close();
in.close();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
}
}
在web.xml中对上面的servlet访问路径配置
<servlet>
<servlet-name>downLoadServlet</servlet-name>
<servlet-class>com.wen.servlet.DownLoadServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>downLoadServlet</servlet-name>
<url-pattern>/down</url-pattern>
</servlet-mapping>
tomact:
访问:
文件上传
Servlet的代码
package com.wen.servlet;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.ProgressListener;
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.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.UUID;
public class FileUploadServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//判断上传的文件是普通表单还是带文件的表单
if (!ServletFileUpload.isMultipartContent(req)) {
return;//终止方法运行,说明这是一个普通的表单,直按返回
}
//创建上传文件的保存路径,建议在WEB-INF路径下,安全,用户无法直接访问上传的文件;
String uploadPath = this.getServletContext().getRealPath("/WEB-INF/upload");
File uploadFile = new File(uploadPath);
if (!uploadFile.exists()) {
uploadFile.mkdir(); //创建这个目录
}
//级存,临时文件
//临时路径,假如文件超过了预期的大小,我们就把他放到一个临时文件中,过几天白动鹏除,或者提醒用户转存为永久
String tmpPath = this.getServletContext().getRealPath("/WEB-INF/tmp");
File file = new File(tmpPath);
if (!file.exists()) {
file.mkdir(); //创建这个临时日录
}
//1.创建DiskFileItemFactory对象,处理文件上传路径或者大小限制的;
DiskFileItemFactory factory = getDiskFileItemFactory(file);
//2.获取ServletFileUpload
ServletFileUpload upload = getServletFileUpload(factory);
//3.处理上传的文件
String msg = null;
try {
msg = uploadParseRequest(upload,req,uploadPath);
} catch (FileUploadException e) {
e.printStackTrace();
}
//servlet请求转发消息
req.setAttribute( "msg",msg);
req.getRequestDispatcher("/info.jsp" ).forward(req,resp);
}
public static DiskFileItemFactory getDiskFileItemFactory(File file) {
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(1024 * 1024);//缓存区大小为1M
factory.setRepository(file);//临时目录的保存目录,需要一个File
return factory;
//通过这个工厂设置一个缓冲区,当上传的文件大于这个缓冲区的时候,将他放到临时文件中;
}
public static ServletFileUpload getServletFileUpload(DiskFileItemFactory factory) {
//2.获取ServletFiLeUpload
ServletFileUpload upload = new ServletFileUpload(factory);
//处理上传的文件,一般都需要通过流来获取,我们可以使川request.getInputStream()。原生态的文件上传流获取,十分麻烦
//通过ServletFiLelpLoad对象的构造方法或setFiLe工temFactory()方法设置servletFiLeupLoad对象的fiLeItemFactory属性。
//监听文件上传进度;
upload.setProgressListener(new ProgressListener() {
@Override
//pContentLength :文件大小 //pBytesRead: 经读取到的文件人小
public void update(long pBytesRead, long pContentLength, int pItems) {
System.out.println("总大小:" + pContentLength + "已上传:" + pBytesRead);
}
});
//处理乱码问题
upload.setHeaderEncoding("UTF-8");
//设置单个文件的最大值
upload.setFileSizeMax(1024 * 1024 * 10);
//设置总共能够上传文件的大小
//1024 = 1kb* 1024 =.1M* 10 = 10M
upload.setSizeMax(1024 * 1024 * 10);
return upload;
}
public static String uploadParseRequest(ServletFileUpload upload, HttpServletRequest request, String uploadPath)
throws FileUploadException, IOException {
String msg = "";
//3.把前端请求解析,封装成一个FileItem对象
List<FileItem> fileItems = upload.parseRequest(request);
for (FileItem fileItem : fileItems) {//判断上传的文件是普通的表单还是带文件的表单
if (fileItem.isFormField()) {//getFieLdName指的是前端表单控件的name ;
String name = fileItem.getFieldName();
String value = fileItem.getString("UTF-8");//处理乱码
System.out.println(name + ":" + value);
} else { //判断他是上传的文件
//处理文件
String uploadFileName = fileItem.getName();
System.out.println("上传的文件名:"+uploadFileName);
//可能存在文件名不合法的情况
if (uploadFileName.trim().equals("") || uploadFileName == null) {
continue;
}
//获得上传文件后缀名
String fileExtName = uploadFileName.substring(uploadFileName.lastIndexOf(".") + 1);
//获得上传文件名
String fileName = uploadFileName.substring(uploadFileName.lastIndexOf("\\") + 1);
/*
如果文件后缀名fileExtName不是我们所需要的
就直接return,不处理,告诉用户文件类型不对。*/
System.out.println("文件信息[文件名:" + fileName + "---文件类型" + fileExtName + "]");
String uuidPath = UUID.randomUUID().toString();
//l存到哪?uploadPath
//文件真实存在的路径realPath
String realPath = uploadPath + "/" + uuidPath;
//给每个文件创建一个对应的文件夹
File realPathFile = new File(realPath);
if (!realPathFile.exists()) {
realPathFile.mkdir();
}
//获得文件上传的流
InputStream inputstream = fileItem.getInputStream();
//创建一个文件输出流
//realPath =真实的文件灭;
//差了一个文件;加上输出文件的名宁+"/"+uuidFiLeName
FileOutputStream fos = new FileOutputStream(realPath + "/" + fileName);
//创建一个缓冲区
byte[] buffer = new byte[1024 * 1024];
//判断是否读取完毕
int len = 0;
//如果大于0说明还存在数据;
while ((len = inputstream.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
//关闭流
fos.close();
inputstream.close();
msg = "文件上传成功!";
fileItem.delete(); //上传成功,清除临时文件
}
}
return msg;
}
}
jsp代码:
<%--
Created by IntelliJ IDEA.
User: wjh0
Date: 2020/9/11
Time: 12:26
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>upload</title>
</head>
<body>
<%--通过表单上传文件
get:上传文件大小有限制
post:上传文件大小没有限制
--%>
<form action="${pageContext.request.contextPath}/upload.do" enctype="multipart/form-data" method="post">
<p>上传用户: <input type="text" name="username" ></p>
<p><input type="file" name="file1"></p>
<p><input type="file" name="file1"></p>
<p><input type="submit"> | <input type="reset"></p>
</form>
</body>
</html>
在web.xml中加入上面servlet的访问路径
<servlet>
<servlet-name>FileUploadServlet</servlet-name>
<servlet-class>com.wen.servlet.FileUploadServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FileUploadServlet</servlet-name>
<url-pattern>/upload.do</url-pattern>
</servlet-mapping>
info.jsp的内容
<%--
Created by IntelliJ IDEA.
User: wjh0
Date: 2020/9/11
Time: 18:36
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<p>${msg}</p>
</body>
</html>
tomcat的访问路径和访问情况不在书写,上传的servlet中将上传的过程写作3个方法在dopost中调用,
也可以书写在一起,代码量较大。