Java-Maven实现简单的文件上传下载(菜鸟一枚、仅供参考)

2023-03-14,,

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-Maven实现简单的文件上传下载(菜鸟一枚、仅供参考).doc》

下载本文的Word格式文档,以方便收藏与打印。