文件的上传与下载之方式1:Servlet

时间:2021-08-31 20:57:47

**方式一:**servlet方式

首先是jar包的导入
文件的上传与下载之方式1:Servlet

前端页面:
<body>
<!--注意:上传方式应该是post请求且enctype的值是以二进制流的方式上传-->
<form method="post" action="upload" enctype="multipart/form-data">
文件上传者: <input type="text" name="username"><br />
文件上传:
<div id="div1">
<div>
<input type="file" name="files" />
</div>
</div>
<input type="button" value="添加" onclick="addfile()"> <input
type="submit" value="提交" />

</form>
<!--主要是上面部分代码就行-->
<!--js代码是应对多个文件上传-->
<script type="text/javascript">
function addfile() {
var files = document.getElementById("div1");
var divEle = document.createElement("div");
var inputEle = document.createElement("input");
inputEle.type = "file";
inputEle.name = "files";
var aEle = document.createElement("a");
aEle.innerHTML = "删除";
aEle.href = "javascript:void()";
aEle.setAttribute("onclick", "del(this)");
divEle.appendChild(inputEle);
divEle.appendChild(aEle);
files.appendChild(divEle);
}
function del(obj) {
obj.parentNode.parentNode.removeChild(obj.parentNode);
}
</script>
</body>

接下来是上传的java代码

package com.zdl;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

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 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;

@WebServlet("/upload")
public class FileUpload extends HttpServlet {

private static final long serialVersionUID = 1L;

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

System.getProperty("java.io.tmpdir");
req.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
String savepath = this.getServletContext().getRealPath("WEB-INF/upload");
List<String> fileType = Arrays.asList("doc", "docx", "txt", "jpg", "png", "zip");
PrintWriter out = resp.getWriter();

DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(1024 * 1024);// 设置缓存大小,超过级缓存
factory.setRepository(new File(this.getServletContext().getRealPath("WEB-INF/temp")));// 设置的缓存目录
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setFileSizeMax(1024 * 1024 * 50);// 控制单个文件大小
upload.setSizeMax(1024 * 1024 * 200);// 控制多有文件大小
// 设置上传进度
upload.setProgressListener(new ProgressListener() {

@Override
public void update(long pBytesRead, long pContentLength, int pItems) {
System.out.println("文件已读取:" + pBytesRead + "--文件大小:" + pContentLength + "--第几项:" + pItems);

}
});
if (ServletFileUpload.isMultipartContent(req)) {
try {
List<FileItem> fileItems = upload.parseRequest(req);
for (FileItem fileItem : fileItems) {
if (fileItem.isFormField()) {
String name = fileItem.getFieldName();
String value = fileItem.getString("utf-8");
System.out.println(name + "---" + value);
} else {
InputStream in = fileItem.getInputStream();
String filename = fileItem.getName();// 可能是全路径名称浏览器兼容性(IE)
// filename =
// filename.substring(filename.lastIndexOf("\\")+1);
System.out.println(filename);
String realFileName = makeFileName(filename);
if (filename == null || filename.trim().equals("")) {
continue;
}
/*
* boolean bool = filename.endsWith(".docx"); if (!bool)
* { out.print(filename+ ":文件类型有误,请检查文件后缀名"); continue;
* }
*/

String ext = filename.substring(filename.lastIndexOf(".") + 1);
if (!fileType.contains(ext)) {
out.print(filename + ":文件类型有误,请检查文件后缀名<br/>");
continue;
}

String realPath = makeDirectory(savepath, realFileName);
FileOutputStream fos = new FileOutputStream(realPath + "\\" + realFileName);
byte[] b = new byte[1024];
int len = 0;
while ((len = in.read(b)) != -1) {
fos.write(b, 0, len);
}
fos.close();
in.close();
fileItem.delete();//删除缓存文件
out.print(filename+":上传完成<br>");
}
}

} catch (FileUploadException e) {
e.printStackTrace();
}
}
out.flush();
out.close();
}
//可用来处理文件同名覆盖的问题
public String makeFileName(String filename) {

return UUID.randomUUID().toString() + "-" + filename;
}
//为上传的文件分配文件夹
public String makeDirectory(String savepath, String filename) {

int hash = filename.hashCode();
int dir1 = hash & 0xf;// 获得数字0-15
int dir2 = (hash & 0xf) >> 4;// 右移四位

String realPath = savepath + "\\" + dir1 + "\\" + dir2;
File dir = new File(realPath);
if (!dir.exists()) {
dir.mkdirs();
}
return realPath;
}
}

然后就是下载的前端页面


<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

<body>
<h3>文件列表</h3>
<c:if test="${map != null }">
<c:forEach items="${map }" var="m">
<c:url value="downfileservlet" var="downfile">
<c:param name="filename" value="${m.value }"></c:param>
</c:url>
<a href="${downfile }">${m.key }</a><br/>
</c:forEach>
</c:if>

</body>

下载的java代码

package com.zdl;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.URLEncoder;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/downfileservlet")
public class DownFile extends HttpServlet{

private static final long serialVersionUID = 1L;

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

doPost(req, resp);
}

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

req.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");

//获取要下载的文件的名字
//1获取到upload的目录
String savepath = req.getServletContext().getRealPath("/WEB-INF/upload");
//2获取要下载的文件(带有UUID生成的文件名)
String realfilename =req.getParameter("filename");
System.out.println("获取到的名字"+realfilename);
//3去掉uuid生成的前缀
String filename = realfilename.substring(realfilename.indexOf("_")+1);
System.out.println("去掉uuid生成的前缀"+filename);
//4真正的保存路径
String realpath = makeDirectory(savepath,filename);
System.out.println("真正的保存路径"+realpath);
//5下载文件的路径
System.out.println(realpath+"\\"+realfilename);
//发送给浏览器响应头(告诉浏览器你的是一个文件)
resp.setHeader("content-disposition", "attachment;filename="+URLEncoder.encode(filename,"utf-8"));
//6读取文件并发送给浏览器
FileInputStream fis = new FileInputStream(realpath+"\\"+realfilename);
System.out.println(fis);
//7.获取字节输出流
OutputStream os = resp.getOutputStream();
byte[] b = new byte[1024];
int len =0;
while((len=fis.read(b))!=-1){
os.write(b,0,len);
}
os.close();
fis.close();

}

//找到之前文件所保存的文件夹下的目录
private String makeDirectory(String savepath, String filename) {

System.out.println("传来的名字:"+filename);
int hash = filename.hashCode();
System.out.println("下载的:"+hash);
int dir1 = hash&0xf;
int dir2 = (hash&0xf0)>>4;

String realpath = savepath+"\\"+dir1+"\\"+dir2;
File dir = new File(realpath);
if(!dir.exists()){
//dir.mkdirs();
System.out.println("该文件的目录不存在");
}
return realpath;
}
}

这是一个所有文件的展示的java代码

package com.zdl;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/listfileservlet")
public class ListFile extends HttpServlet{

private static final long serialVersionUID = 1L;

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

req.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");

String upload = req.getServletContext().getRealPath("/WEB-INF/upload");
File dir = new File(upload);
//保存所有遍历到的文件,并存入到改集合中
HashMap<String, String> map = new HashMap<String, String>();

if (dir != null) {
listUpload(dir, map);
req.setAttribute("map", map);
}
req.getRequestDispatcher("listfile.jsp").forward(req, resp);
}

//这是一个递归遍历文件夹
public void listUpload(File dir,HashMap<String , String> map){

File[] files = dir.listFiles();
if (files !=null&&files.length>0) {
for (File file : files) {
if (file.isDirectory()) {
listUpload(file, map);//调用自己
}else {
String filename = file.getName();
filename = filename.substring(filename.lastIndexOf("_")+1);
map.put(filename, file.getName());
}
}
}
}
}