当前位置:网站首页>web项目文件简单上传和下载
web项目文件简单上传和下载
2022-07-26 17:03:00 【码上心动】
文件简单上传和下载
一、文件上传
- 需要jar包(网上一搜都能下载)

- 前端代码
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<!-- 指定了base标签 -->
<base href="<%=request.getContextPath()+"/"%>>">
<style type="text/css">
input[type="submit"] {
outline: none;
border-radius: 5px;
cursor: pointer;
background-color: #31B0D5;
border: none;
width: 70px;
height: 35px;
font-size: 20px;
}
img {
border-radius: 50%;
}
form {
position: relative;
width: 200px;
height: 200px;
}
input[type="file"] {
position: absolute;
left: 0;
top: 0;
height: 200px;
opacity: 0;
cursor: pointer;
}
</style>
<script type="text/javascript">
function prev(event) {
//获取展示图片的区域
var img = document.getElementById("prevView");
//获取文件对象
var file = event.files[0];
//获取文件阅读器: Js的一个类,直接使用即可
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function () {
//给img的src设置图片url
img.setAttribute("src", this.result);
}
}
</script>
</head>
<body>
<!-- 表单的enctype属性要设置为multipart/form-data
enctype="multipart/form-data" 表示提交的数据是多个部分构造,有文件和文本
-->
<form action="fileUploadServlet" method="post" enctype="multipart/form-data">
图: <img src="2.jpg" alt="" width="200" height="200" id="prevView">
<input type="file" name="pic" id="" value="" οnchange="prev(this)"/>
名: <input type="text" name="name"><br/>
<input type="submit" value="上传"/>
</form>
</body>
</html>
- servlet代码
package mzq.servlet;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import utils.WebUtils;
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.IOException;
import java.util.List;
import java.util.UUID;
public class FileUploadServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//System.out.println("FileUploadServlet 被调用...");
//1. 判断是不是文件表单(enctype="multipart/form-data")
if (ServletFileUpload.isMultipartContent(request)) {
//System.out.println("OK");
//2. 创建 DiskFileItemFactory 对象, 用于构建一个解析上传数据的工具对象
DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
//3. 创建一个解析上传数据的工具对象
ServletFileUpload servletFileUpload =
new ServletFileUpload(diskFileItemFactory);
//解决接收到文件名是中文乱码问题
servletFileUpload.setHeaderEncoding("utf-8");
//4. 关键的地方, servletFileUpload 对象可以把表单提交的数据text / 文件
// 将其封装到 FileItem 文件项中
try {
List<FileItem> list = servletFileUpload.parseRequest(request);
for (FileItem fileItem : list) {
//System.out.println("fileItem=" + fileItem);
//判断是不是一个文件
if (fileItem.isFormField()) {
//如果是true就是文本 input text
String name = fileItem.getString("utf-8");
} else {
//是一个文件
//用一个方法
//获取上传的文件的名字
String name = fileItem.getName();
System.out.println("上传的文件名=" + name);
//把这个上传到 服务器的 temp下的文件保存到你指定的目录
//1.指定一个目录 , 就是我们网站工作目录下
String filePath = "/upload/";
//2. 获取到完整目录 [io/servlet基础]
// 这个目录是和你的web项目运行环境绑定的. 是动态.
String fileRealPath =
request.getServletContext().getRealPath(filePath);
//3. 创建这个上传的目录=> 创建目录?=> Java基础
// 老师思路; 我们也一个工具类,可以返回 /2024/11/11 字符串
File fileRealPathDirectory = new File(fileRealPath + WebUtils.getYearMonthDay());
if (!fileRealPathDirectory.exists()) {
//不存在,就创建
fileRealPathDirectory.mkdirs();//创建
}
//4. 将文件拷贝到fileRealPathDirectory目录
// 构建一个上传文件的完整路径 :目录+文件名
// 对上传的文件名进行处理, 前面增加一个前缀,保证是唯一即可, 不错
name = UUID.randomUUID().toString() + "_" + name;
String fileFullPath = fileRealPathDirectory + "/" +name;
fileItem.write(new File(fileFullPath));
//5. 提示信息
response.setContentType("text/html;charset=utf-8");
response.getWriter().write("上传成功~");
}
}
} catch (Exception e) {
e.printStackTrace();
}
} else {
System.out.println("不是文件表单...");
}
}
private void saveFile(){
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
}
- WebUtils
import java.time.LocalDateTime;
public class WebUtils {
public static String getYearMonthDay() {
//如何得到当前的日期-> java基础 日期 三代类
LocalDateTime ldt = LocalDateTime.now();
int year = ldt.getYear();
int monthValue = ldt.getMonthValue();
int dayOfMonth = ldt.getDayOfMonth();
String yearMonthDay = year + "/" + monthValue + "/" + dayOfMonth + "/";
return yearMonthDay;
}
}
注意:
文件上传,创建web/upload的文件夹,在tomcat启动时,没有在out目录下 创建 对应的upload文件夹,原因是tomcat对应空目录是不会在out下创建相应目录的,所以,只需在upload目录下,放一个文件即可, 这个是Idea + Tomcat的问题,实际开发不会存在
二、文件下载
- 前端简单代码
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>文件下载</title>
<base href="<%=request.getContextPath()+"/"%>>">
</head>
<body>
<h1>文件下载</h1>
<a href="fileDownLoadServlet?name=1.jpg">点击下载图片</a><br/><br/>
<%--1.jpg 为你服务端所要下载的文件名 这里服务端所放位置是download下--%>
</body>
</html>
- FileDownloadServlet
package mzq.servlet;
import org.apache.commons.io.IOUtils;
import sun.misc.BASE64Encoder;
import javax.servlet.ServletContext;
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.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
public class FileDownloadServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1. 先准备要下载的文件[假定这些文件是公共的资源]
// 重要: 保证当我们的tomcat启动后,在工作目录out下有download文件夹, 并且有可供下载的文件!!
// 如果你没有看到你创建的download在工作目录out下 rebuild project -> restart, 就OK
//2. 获取到要下载的文件的名字
request.setCharacterEncoding("utf-8");
String downLoadFileName = request.getParameter("name");
//System.out.println("downLoadFileName= " + downLoadFileName);
//3. 给http响应,设置响应头 Content-Type , 就是文件的MIME
// 通过servletContext 来获取
ServletContext servletContext = request.getServletContext();
String downLoadPath = "/download/"; //下载目录从 web工程根目录计算 /download/1.jpg
String downLoadFileFullPath = downLoadPath + downLoadFileName;
String mimeType = servletContext.getMimeType(downLoadFileFullPath);
System.out.println("mimeType= " + mimeType);
response.setContentType(mimeType);
//4. 给http响应,设置响应头 Content-Disposition
// 这里考虑的细节比较多,比如不同的浏览器写法不一样,考虑编码
// ff 是 文件名中文需要 base64, 而 ie/chrome 是 URL编码
// 这里我们只需知道原理
//(1)如果是Firefox 则中文编码需要 base64
//(2)Content-Disposition 是指定下载的数据的展示形式 , 如果attachment 则使用文件下载方式
//(3)如果是其他(主流ie/chrome) 中文编码使用URL编码
if (request.getHeader("User-Agent").contains("Firefox")) {
// 火狐 Base64编码
response.setHeader("Content-Disposition", "attachment; filename==?UTF-8?B?" +
new BASE64Encoder().encode(downLoadFileName.getBytes("UTF-8")) + "?=");
} else {
// 其他(主流ie/chrome)使用URL编码操作
response.setHeader("Content-Disposition", "attachment; filename=" +
URLEncoder.encode(downLoadFileName, "UTF-8"));
}
//5. 读取下载的文件数据,返回给客户端/浏览器
//(1) 创建一个和要下载的文件,关联的输入流
InputStream resourceAsStream =
servletContext.getResourceAsStream(downLoadFileFullPath);
//(2) 得到返回数据的输出流 [因为返回文件大多数是二进制(字节), IO java基础]
ServletOutputStream outputStream = response.getOutputStream();
//(3) 使用工具类,将输入流关联的文件,对拷到输出流,并返回给客户端/浏览器
IOUtils.copy(resourceAsStream, outputStream);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
}
边栏推荐
- [metauniverse OMI theory] analyze Web3 risk challenges and build Web3 ecological security
- 我们被一个 kong 的性能 bug 折腾了一个通宵
- [training day3] delete
- URL jump vulnerability
- CCS tm4c123 new project
- AI遮天传 ML-集成学习
- Ascend目标检测与识别-定制自己的AI应用
- 我要开中信的证券账户找渠道的经理开安全吗?
- 【集训Day2】cinema ticket
- 6-19 vulnerability exploitation -nsf to obtain the target password file
猜你喜欢

JS closure simulates private variable interview questions and immediately executes function Iife

Heavy announcement! Icml2022 Awards: 15 outstanding papers, selected by Fudan University, Xiamen University and Shanghai Jiaotong University

GAN (Generative Adversarial Network,GAN)生成式对抗网络

【集训Day1】 Dwarves line up
![[template] segment tree 1](/img/60/9f73d00223c8878ffd8513b3b9adf7.jpg)
[template] segment tree 1

跨站点请求伪造(CSRF)

Machine learning by Li Hongyi 2. Regression

解决哈希冲突的几种方式

JS function scope variables declare that the variables that promote the scope chain without VaR are global variables

【集训Day3】section
随机推荐
点云目标检测KITTI数据集bin文件可视化,一站式解决
On the growth of data technicians
国际象棋机器人夹断7岁男孩手指,原因是「棋手违反安全规则」?
Centos安装docker以及mysql和redis环境
AI zhetianchuan ml integrated learning
Spark data format unsafe row
4、 Service communication principle, code implementation
徽商期货网上开户安全吗?开户办理流程是怎样的?
长征证券开户安全吗?
JS 函数作用域 变量声明提升 作用域链 不加var的变量,是全局变量
uni-app
We were tossed all night by a Kong performance bug
Summer Challenge openharmony greedy snake based on JS
Three ways of de duplication in SQL
Pay attention to the traffic safety warning of tourism passenger transport issued by the Ministry of public security
9、 Alternative implementation of client for service communication
The diagram of user login verification process is well written!
5、 Parameter server principle, code implementation
JS recursive Fibonacci sequence deep cloning
Mondriaans‘s Dream(状态压缩DP)