Java-Maven实现简单的文件上传下载(菜鸟一枚、仅供参考)
1、JSP页面代码实现
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>UploadDown</title>
</head>
<body>
<%
if(null==session.getAttribute("currentUser")){
System.out.print("ddd");
response.sendRedirect("/login");
return;
}else{
System.out.print("yyy");
}
%>
<div align="center">
<form action="${pageContext.request.contextPath }/file/upload"
method="post" enctype="multipart/form-data">
<input type="file" name="file" width="120px">
<input type="submit" value="上传">
</form>
<br>
</div> <div>
<table border="1px" bordercolor="yellow" align="center">
<tr>
<th colspan="5" style="font-size: 25px">目录下可下载文件</th>
</tr>
<tr>
<th width="66px">序号</th>
<th width="150px">文件</th>
<th width="150px">大小</th>
<th width="200px">上传时间</th>
<th width="150px">下载</th>
</tr>
<c:forEach items="${fileList }" var="file" varStatus="s"> <jsp:useBean id="dateValue" class="java.util.Date"/>
<jsp:setProperty name="dateValue" property="time" value="${file.lastModified()}"/> <tr>
<td align="center">${s.count}</td>
<td align="center">${file.getName() }</td>
<td align="center">
<fmt:formatNumber type="number" value="${file.length()/1024.00}" pattern="#0.00"/> KB
</td>
<td align="center">
<fmt:formatDate value="${dateValue}" pattern="yyyy-MM-dd HH:mm:ss"/>
</td>
<td align="center">
<input type="button" value="下载" onclick="window.location.href='${pageContext.request.contextPath }/file/down?filename=${file.getName()}'">
<input type="button" value="删除" onclick="window.location.href='${pageContext.request.contextPath }/file/deleteFile?filename=${file.getName()}'"> <%-- <button>
<a href="${pageContext.request.contextPath }/file/deleteFile?filename=${file.getName()}" style="text-decoration: none">删除</a>
</button> --%>
</td>
</tr>
</c:forEach>
</table>
</div>
</body>
<canvas id="canvas" style="position: fixed;"></canvas>
<script src="./js/js1.js"></script>
<style type="text/css">
body{
background-image: url(./js/bg1.jpeg);
background-size:cover;
}
</style>
</html>
2、上传下载代码实现
package com.chao.controller; import com.chao.utils.PathUtil;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest; @Controller
@RequestMapping({ "file" })
public class UploadDownController {
@RequestMapping
public String toIndex(Model model) throws Exception {
String path = PathUtil.static_root;
File file = new File(path);
List fileList = new ArrayList(); if (file != null) {
if (file.isDirectory()) {
File[] fileArray = file.listFiles();
if ((fileArray != null) && (fileArray.length > 0))
for (File f : fileArray)
fileList.add(f);
} else {
System.out.println("目录不存在!");
}
}
model.addAttribute("fileList", fileList);
model.addAttribute("path", path);
return "index";
} @RequestMapping(value = { "upload" }, method = { org.springframework.web.bind.annotation.RequestMethod.POST })
@ResponseBody
public void upload(HttpServletRequest request, HttpServletResponse response) throws Exception {
MultipartRequest multipartRequest = (MultipartRequest) request;
MultipartFile file = multipartRequest.getFile("file"); if ((file == null) || (file.isEmpty())) {
response.setCharacterEncoding("GB2312");
PrintWriter out = response.getWriter();
out.print("<script>alert('请选择上传文件!'); window.location='/file' </script>");
out.flush();
out.close();
} else {
String fileName = file.getOriginalFilename();
String path = PathUtil.static_root; File dir = new File(path, fileName);
if (!dir.getParentFile().exists()) {
dir.getParentFile().mkdirs(); dir.createNewFile();
} else {
dir.createNewFile();
} file.transferTo(dir);
response.sendRedirect("/file");
}
} @RequestMapping({ "down" })
public void down(String filename, HttpServletRequest request, HttpServletResponse response) throws Exception {
String path = PathUtil.static_root;
String downFileName = new String(filename.getBytes("ISO8859-1"), "utf-8"); String fileName = path + File.separator + downFileName; InputStream bis = new BufferedInputStream(new FileInputStream(new File(fileName)));
response.addHeader("Content-Disposition", "attachment;filename=" + filename);
response.setContentType("multipart/form-data"); BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
int len = 0;
while ((len = bis.read()) != -1) {
out.write(len);
out.flush();
}
out.close();
} @RequestMapping({ "deleteFile" })
public String deleteFile(String filename) throws Exception {
String path = PathUtil.static_root;
filename = new String(filename.getBytes("ISO8859-1"), "utf-8");
String fileName = path + File.separator + filename; File file = new File(fileName);
if ((file.exists()) && (file.isFile()))
file.delete();
else {
return "error";
}
return "redirect:/file";
}
}
3、文件上传环境路径判断
package com.chao.utils; public class PathUtil { public static final String WINDOWS_STATIC = "D:\\uploadfile";// Windows静态文件路径 public static final String LINUX_STATIC = "/uploadfile";// Linux静态文件路径 public static String static_root = null; static {
String system = System.getProperties().getProperty("os.name"); // 获取系统类型
if (system.contains("Windows"))
static_root = WINDOWS_STATIC;
if (system.contains("Linux"))
static_root = LINUX_STATIC;
}
}
4、mysql数据库
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0; -- ----------------------------
-- Table structure for users
-- ----------------------------
DROP TABLE IF EXISTS `users`;
CREATE TABLE `users` (
`id` int(0) NOT NULL AUTO_INCREMENT,
`username` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
`password` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 2 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic; SET FOREIGN_KEY_CHECKS = 1;
Java-Maven实现简单的文件上传下载(菜鸟一枚、仅供参考)的更多相关文章
- Java实现一个简单的文件上传案例
Java实现一个简单的文件上传案例 实现流程: 1.客户端从硬盘读取文件数据到程序中 2.客户端输出流,写出文件到服务端 3.服务端输出流,读取文件数据到服务端中 4.输出流,写出文件数据到服务器硬盘 ...
- Java 客户端操作 FastDFS 实现文件上传下载替换删除
FastDFS 的作者余庆先生已经为我们开发好了 Java 对应的 SDK.这里需要解释一下:作者余庆并没有及时更新最新的 Java SDK 至 Maven 中央仓库,目前中央仓库最新版仍旧是 1.2 ...
- Java实现FTP批量大文件上传下载篇1
本文介绍了在Java中,如何使用Java现有的可用的库来编写FTP客户端代码,并开发成Applet控件,做成基于Web的批量.大文件的上传下载控件.文章在比较了一系列FTP客户库的基础上,就其中一个比 ...
- JAVA中使用FTPClient实现文件上传下载
在JAVA程序中,经常需要和FTP打交道,比如向FTP服务器上传文件.下载文件,本文简单介绍如何利用jakarta commons中的FTPClient(在commons-net包中)实现上传下载文件 ...
- Java语言实现简单FTP软件------>上传下载管理模块的实现(十一)
1.上传本地文件或文件夹到远程FTP服务器端的功能. 当用户在本地文件列表中选择想要上传的文件后,点击上传按钮,将本机上指定的文件上传到FTP服务器当前展现的目录,下图为上传子模块流程图 选择好要上传 ...
- JAVA中使用FTPClient实现文件上传下载实例代码
一.上传文件 原理就不介绍了,大家直接看代码吧 ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 ...
- Java语言实现简单FTP软件------>上传下载队列窗口的实现(七)
1.首先看一下队列窗口的界面 2.看一下上传队列窗口的界面 3.看一下下载队列窗口的界面 4.队列窗口的实现 package com.oyp.ftp.panel.queue; import stati ...
- Java实现FTP与SFTP文件上传下载
添加依赖Jsch-0.1.54.jar <!-- https://mvnrepository.com/artifact/com.jcraft/jsch --> <dependency ...
- java中io流实现文件上传下载
新建io.jsp <%@ page language="java" contentType="text/html; charset=UTF-8" page ...
- java操作FTP,实现文件上传下载删除操作
上传文件到FTP服务器: /** * Description: 向FTP服务器上传文件 * @param url FTP服务器hostname * @param port FTP服务器端口,如果默认端 ...
随机推荐
- 解决Mac安装Homebrew失败
首先使用Homebrew官网的安装shell命令安装: /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebr ...
- rabbitmq的Exchange类型案例
一.direct(将消息转发到指定Routing key的Queue上,Routing key的解析规则为精确匹配) publish代码 consumer代码,绑定了另一个队列 优先启动publish ...
- CTF学习笔记(三)php部分
三.常见PHP用法与漏洞 (〇)php的备份文件与phps php的备份文件一般是*.php.bak,在根目录下输入/index.php.bak, 下载 备份文件. phps文件就是php的源代码文件 ...
- 服务器consul与本地服务健康检查不通问题解决
(125条消息) 服务器consul与本地服务健康检查不通问题解决_向往鸟的博客-CSDN博客_consul健康检查失败 .MathJax, .MathJax_Message, .MathJax_Pr ...
- ES-索引库
数据准备 本次学习涵盖ES简单查询,聚合查询,所以在创建测试库时会可以涵盖一些个性化字段,用于学习搜索用法 索引创建 几个疑问 1.能否用中文命名 安排:我用"蓝闪test",中英 ...
- 正确处理iOS从下方滑出滚动视图
本文提供 Demo下载 在iOS 11开始,从最早的地图应用到最近的捷径,陆续有系统应用使用从下方滑出列表的形式,这种系统提供的圆角风格视图用手势划出和隐藏时非常自然流畅.国内的一些应用也跟进了这种交 ...
- 【未完】【DDR系列文章收集】
资料来源 1.https://zhuanlan.zhihu.com/p/343262874 (1)主要讲DRAM刷新的内容: 为什么需要刷新(漏电流导致电容电荷的流失)? 刷新的本质(对存储数据的电容 ...
- CAD中相交线怎样打断?CAD打断相交线步骤
在CAD设计过程中,如果想要打断图纸中相交线该如何操作呢?大家第一个想到的是不是CAD打断命令?没错,CAD打断命令是可以实现的,但是过于麻烦,今天小编来给大家分享一个更简单的方法,那就是浩辰CAD软 ...
- Java8函数式编程(A)
将行为作为数据传递 函数编程的最直接的表现,莫过于将函数作为数据自由传递,结合泛型推导能力,使代码表达能力获得飞一般的提升. Java8怎么支持函数式编程? 主要有三个核心概念: 函数接口(Funct ...
- 【Anaconda】Jupyter 中添加 Anaconda 环境
两种方法: 1. 安装 nb_conda_kernels,将所有 conda 环境同步至 Jupyter Notebook,参考『Jupyter notebook选择conda环境 - 简书』. 2. ...