java实现文件上传和下载,支持拖拽上传
![在这里插入图片描述](https://img-blog.csdnimg.cn/fccacd907213423f9d11c1901d5dffc2.png#pic_center)
主页
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Document</title>
<script type="text/javascript" src="jquery-1.8.3.js"></script>
<style>
* {
padding: 0px;
margin: 0px;
}
.form{
width:69.5%;
height:50%;
margin-left: 14%;
}
body {
height: 100px;
background: #394E48;
font-size: 14px;
font-family: "微软雅黑";
}
.drag-area {
width: 60%;
height: 100px;
border: 3px dashed #fff;
text-align: center;
line-height: 100px;
color: #fff;
font-size: 36px;
font-weight: 700;
}
.dj{
width: 50px;
height: 50px;
background-color: #ccc;
}
.box {
width: 500px;
height: 500px;
background-color: #ccc;
border: 1px solid black;
line-height: 200px;
position: absolute;
left: 50%;
top: 50%;
margin-top: -100px;
margin-left: -200px;
text-align: center;
display: none;
}
.m1 {
width: 300px;
}
.demo {
width: 900px;
height: 140px;
margin: 50px auto;
}
.drag-area {
width: 100%;
height: 100px;
border: 3px dashed #fff;
text-align: center;
line-height: 100px;
color: #fff;
font-size: 36px;
font-weight: 700;
}
}
.preview div {
width: 195px;
overflow: hidden;
border: 1px dashed silver;
margin-top: 10px;
float: left;
padding: 9px;
text-align: center;
height: 168px;
}
.submit{
width: 40%;
height: 80px;
margin-left: 16%;
background:#0D000000;
font-size: 36px;
color: #fff;
font-weight: 600;
border: 3px dashed #fff;
float:left;
}
.down{
display:block;
font-size: 36px;
color: #fff;
font-weight: 600;
width:20%;
height:148%;
text-decoration:none;
border: 3px dashed #fff;
float:left;
margin-left: 10%;
text-align:center;
line-height:200%;
}
.preview img {
width: 80px;
height: 80px;
}
.title {
text-align: center;
color: #fff;
margin-top: 50px;
}
.title2 {
text-align: center;
color: #fff;
margin-top: 50px;
}
</style>
</head>
<script >
window.onload=()=>{
let oBox=document.querySelector('.drag-area');
let oBox2=document.querySelector('.submit');
document.addEventListener('dragover',ev=>{//当拽离整个文档时
oBox.style.display='block';
ev.preventDefault()
},false);
oBox.addEventListener('dragenter',()=>{
oBox.innerHTML='请松手';
},false);
oBox.addEventListener('dragleave',()=>{
console.log('bbb')
oBox.innerHTML='请拖到这里';
},false);
oBox.addEventListener('drop',ev=>{//松手后执行此函数
console.log("1"+ev.dataTransfer.files)
oBox.style.display='block';
var fileList=ev.dataTransfer.files;
for(var i=0;i<fileList.length;i++){
//此处判断只能上传图片
//if(fileList[i].type.indexOf("image")!=0){
//alert("请上传图片");
//return;
//}
//图片预览 这一步需要判断是什么浏览器 大家自己判断吧
/*************************************/
img1=window.URL.createObjectURL(fileList[i]);
/*************************************/
var str="<div><img src='"+img1+"'/><p>"+fileList[i].name+"</p></div>";
document.getElementById("preview").innerHTML +=str;
}
let data=new FormData();//将数据编译成键值对,通过XMLHttpRequest().send()发送出去。
Array.from(ev.dataTransfer.files).forEach(file=>{
data.append('f1',file)
oBox.innerHTML=`${file.name}上传中<meter id="m1" value="" min="0" max="100"></meter>`;
});
let ajax=new XMLHttpRequest();//用于在后台与服务器交互数据
ajax.open('POST',"i",true);//初始化HTTP请求
ajax.upload.addEventListener('progress',ev=>{//监听上传的进度
let meter=document.getElementById('m1');
meter.value=ev.loaded/ev.total*100
},false)
ajax.send(data)//发送HTTP请求
ajax.onreadystatechange=()=>{
if(ajax.readyState==4){
if(ajax.status>=200&&ajax.status<300||ajax.status==304){
// location.href= "http://22.126.30.38:8085/Drop/message.jsp";
oBox.innerHTML='上传成功'+ajax.readyState+"__"+ajax.status;
}else{
oBox.innerHTML='上传失败'+ajax.readyState+"__"+ajax.status;
//alert('失败')
}
}
}
ev.preventDefault()
},false);
oBox2.addEventListener('click',ev=>{
//if(${message}!="上传成功"){
//alert(555);
//}
},false);
}
</script>
<body>
<h1 class="title">Java实现<我的网盘></br><h2 class="title2">浪里小白[G'le]龙最新力作!</h2></h1>
<div class="demo">
<div class="drag-area" id="upload-area" onclick="getFile()">点击或将文件拖拽到这里</div>
<!-- 图片预览 -->
<div id="preview" class="preview"></div>
<div id="my">${message}.</div>
</div>
<form action="UploadServlet" enctype="multipart/form-data" method="post" class="form" id="form1" onsubmit="return check()">
<input name="img" type="file" id="getF" onchange="clickF()" style="display:none"/>
<input type="submit" value="上传" class="submit"/><a href="list" class="down">下载</a>
<div class="dj"></div>
<%
//判断保存在request范围内的对象是否为空
if(request.getAttribute("message")!=null){
//out.println("<script>alert('"+request.getAttribute("message")+"');</script>");
out.println("<script> let oBox=document.querySelector('.drag-area');oBox.innerHTML='上传成功';</script>");
}else{
//out.println("<script>alert('上传文件出错,请重新上传');</script>");
}
%>
<script>
function check(){
var web_name = $("#getF").val().replace(/s+/g,"");
if(web_name == null || web_name == ""){
//alert("网站名称不能为空");
document.querySelector('.drag-area').innerHTML='文件上传错误';
return false;
}
}
//点击按钮后禁止页面刷新。
//</form><iframe id="iFrame" name="iFrame" src="about:blank" style="display:none;"></iframe>
//var form1 = document.getElementById('form1');
//console.log(form1);
//$("#form1").attr("target","iFrame");
function getFile(){ $("#getF").click(); } //实现点击指定区域打开<input type="file">文件上传对话框,并添加文件
var filename="";
function clickF() { filename=$("#getF").val(); //从<input type="file">标签中获取文件名
var filenames=filename.split("\\");
filename=filenames[filenames.length-1];
//$("#lb").text(filename);
document.getElementById('upload-area').innerText=filename;}
</script>
</body>
</html>
data.jsp
<%@page import="java.util.UUID"%>
<%@page import="org.apache.commons.fileupload.FileItem"%>
<%@page import="java.util.Iterator"%>
<%@page import="java.util.List"%>
<%@page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%>
<%@page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%>
<%@page import="org.apache.commons.fileupload.FileItemFactory"%>
<%@page import="java.io.File"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
/*
1、文件上传:
*/
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
//获取文件路径
String strPath=request.getRealPath("/")+"/upload";
File file =new File(strPath);
if(!file.exists())file.mkdirs();
FileItemFactory factory=new DiskFileItemFactory();
ServletFileUpload upload=new ServletFileUpload(factory);
//从请求对象中获取文件信息
List items= upload.parseRequest(request);
if(items!=null){
for(int i=0;i<items.size();i++){
Iterator iterator=items.iterator();
while(iterator.hasNext()){
FileItem item=(FileItem)iterator.next();
if(item.isFormField()){
continue;
}else{
String fileName=item.getName();
Long fileSize=item.getSize();
int pos=fileName.indexOf(".");
String ext=fileName.substring(pos,fileName.length());
fileName=UUID.randomUUID().toString()+ext;
File saveFile=new File(strPath,fileName);
item.write(saveFile);
}
}
}
}
%>
下载页
<%@ page language="java" import="java.util.*"
contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE HTML>
<html>
<head>
<title>下载文件显示页面</title>
</head>
<body>
<!-- 遍历Map集合 -->
<c:forEach var="me" items="${fileMap}">
<c:url value="/DownLoadServlet" var="downurl">
<c:param name="filename" value="${me.key}"></c:param>
</c:url>
${me.value}<a href="${downurl}">下载</a>
<br />
</c:forEach>
</body>
</html>
DownLoadServlet
package com.runoob.test;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class DownLoadServlet extends HttpServlet{
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//得到要下载的文件名
String fileName = request.getParameter("filename");
System.out.println("要下载的文件:"+fileName);
//先将str按iso8859-1进行接受,然后按utf-8解码。tomcat如果配置了utf-8编码就不用加,不然会乱码。
//fileName = new String(fileName.getBytes("iso8859-1"),"UTF-8");
System.out.println("要下载的文件2:"+fileName);
//上传的文件都是保存在/WEB-INF/upload目录下的子目录当中
//String fileSaveRootPath=this.getServletContext().getRealPath("/WEB-INF/upload");
String fileSaveRootPath="D:\\Imprint_RW_CD(public)";
// 处理文件名
String realname = fileName.substring(fileName.indexOf("_")+1);
//通过文件名找出文件的所在目录
String path = findFileSavePathByFileName(fileName,fileSaveRootPath);
//得到要下载的文件
File file = new File(path+File.separator+fileName);
//如果文件不存在
if(!file.exists()){
request.setAttribute("message", "您要下载的资源已被删除!!");
request.getRequestDispatcher("/message.jsp").forward(request, response);
return;
}
//设置响应头,控制浏览器下载该文件
response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(realname, "UTF-8"));
//读取要下载的文件,保存到文件输入流
FileInputStream in = new FileInputStream(path + File.separator + fileName);
//创建输出流
OutputStream os = response.getOutputStream();
//设置缓存区
byte[] bytes = new byte[1024];
int len = 0;
while((len = in.read(bytes))>0){
os.write(bytes);
}
//关闭输入流
in.close();
//关闭输出流
os.close();
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
//通过文件名和存储上传文件根目录找出要下载的文件的所在路径
public String findFileSavePathByFileName(String fileName,String fileSaveRootPath){
int hashcode = fileName.hashCode();
int dir1 = hashcode&0xf;
int dir2 = (hashcode&0xf0)>>4;
String dir = fileSaveRootPath;
File file = new File(dir);
System.out.println("保存的文件路径"+file);
if(!file.exists()){
file.mkdirs();
}
return dir;
}
}
列出文件夹中的文件
package com.runoob.test;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ListFileServlet extends HttpServlet{
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//获取上传文件的目录
//String uploadFilePath = this.getServletContext().getRealPath("/k");
String uploadFilePath ="D://Imprint_RW_CD(public)";
System.out.println(uploadFilePath);
//存储要下载的文件名
Map<String, String> fileMap = new HashMap<String, String>();
//递归遍历filepath目录下的所有文件和目录,将文件的文件名存储到map集合中
fileList(new File(uploadFilePath),fileMap);
//将Map集合发送到listfile.jsp页面进行显示
request.setAttribute("fileMap", fileMap);
request.getRequestDispatcher("/down_listfile.jsp").forward(request, response);
}
//递归遍历指定目录下的所有文件
public void fileList(File file,Map fileMap){
//如果file代表的不是一个文件,而是一个目录
if(!file.isFile()){
//列出该目录下的所有文件和目录
File[] files = file.listFiles();
//遍历files[]数组
for (File file2 : files) {
System.out.println("文件"+file2.getName());
//递归
fileList(file2, fileMap);
}
}else{
/* 处理文件名,上传后的文件是以uuid_文件名的形式去重新命名的,去除文件名的uuid_部分
file.getName().indexOf("_")检索字符串中第一次出现"_"字符的位置,如果文件名类似于:9349249849-88343-8344_阿_凡_达.avi
那么file.getName().substring(file.getName().indexOf("_")+1)处理之后就可以得到阿_凡_达.avi部分
*/
String realName = file.getName().substring(file.getName().lastIndexOf("_")+1);
//file.getName()得到的是文件的原始名称,这个名称是唯一的,因此可以作为key,realName是处理过后的名称,有可能会重复
fileMap.put(file.getName(), realName);
}
}
}
UploadServlet
package com.runoob.test;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
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 org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
/**
* Servlet implementation class UploadServlet
*/
// 如果不配置 web.xml ,可以使用下面的代码
@WebServlet("/UploadServlet")
public class UploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
// 上传文件存储目录
//private static final String UPLOAD_DIRECTORY = "upload";
// 上传配置
private static final int MEMORY_THRESHOLD = 1024 * 1024 * 3; // 3MB
private static final int MAX_FILE_SIZE = 1024 * 1024 * 400; // 40MB
private static final int MAX_REQUEST_SIZE = 1024 * 1024 * 500; // 50MB
/**
* 上传数据及保存文件
*/
protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
// 检测是否为多媒体上传
if (!ServletFileUpload.isMultipartContent(request)) {
// 如果不是则停止
PrintWriter writer = response.getWriter();
writer.println("Error: 表单必须包含 enctype=multipart/form-data");
writer.flush();
return;
}
// 配置上传参数
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 = getServletContext().getRealPath("/") + File.separator + UPLOAD_DIRECTORY;
String uploadPath = "D:\\Imprint_RW_CD(public)";
// 如果目录不存在则创建
File uploadDir = new File(uploadPath);
if (!uploadDir.exists()) {
uploadDir.mkdir();
}
try {
// 解析请求的内容提取文件数据
@SuppressWarnings("unchecked")
List<FileItem> formItems = upload.parseRequest(request);
String message="上传成功";
if (formItems != null && formItems.size() > 0) {
// 迭代表单数据
for (FileItem item : formItems) {
// 处理不在表单中的字段
if (!item.isFormField()) {
String fileName = new File(item.getName()).getName();
String filePath = uploadPath + File.separator + fileName;
File storeFile = new File(filePath);
// 在控制台输出文件的上传路径
System.out.println(filePath);
// 保存文件到硬盘
item.write(storeFile);
request.setAttribute("message",message);
//将提示信息保存在request对象中
RequestDispatcher requestDispatcher=request.getRequestDispatcher("up.jsp");
//设置相应返回地址
requestDispatcher.forward(request,response);
System.out.println("2222");
}
}
}
} catch (Exception ex) {
request.setAttribute("message","错误信息: " + ex.getMessage());
}
// 跳转到 message.jsp
//response.addHeader("REDIRECT", "REDIRECT");
//response.addHeader("CONTEXTPATH", "/Drop/message.jsp");
//response.setStatus(HttpServletResponse.SC_FORBIDDEN);
//response.addHeader("Access-Control-Expose-Headers", "REDIRECT,CONTEXTPATH");
//getServletContext().getRequestDispatcher("/message.jsp").forward(request,response);
//response.sendRedirect("/Drop/up.jsp");
//getServletContext().getRealPath("/message.jsp");
}
}