jsp+servlet简单实现上传文件功能(保存目录改进)
作者:广大菜鸟 时间:2023-07-20 17:57:07
1、jsp前端
<%--
Created by IntelliJ IDEA.
User: Lenovo
Date: 2020/6/19
Time: 22:53
Learn from https://www.bilibili.com/video/BV18z411i7gh?t=23&p=192
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>文件上传</title>
</head>
<body>
<!--文件上传对表单的要求-->
<!--
1、表单中的请求提交方式必须是POST
2、表单中应指定所提交的请求位multipart请求,通过在<form/>标签中添加enctype属性
其值为multipart/form-data
3、 表单
-->
<form method="POST" action="http://localhost:8888/hello/UploadImageServlet" enctype="multipart/form-data">
编号<input type="text" name="BNO"></br>
名字<input type="text" name="BNAME"></br>
照片<input type="file" name="picutreUrl"></br>
<input type="submit" value="注册">
</form>
</body>
</html>
2、servlet后台
package Servlet.bookServlet;
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 javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
@WebServlet(name = "UploadImageServlet")
public class UploadImageServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request,response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1、判断请求是不是multipart请求
if(!ServletFileUpload.isMultipartContent(request)){
throw new RuntimeException("当前请求不支持文件上传");
}
System.out.println("开始上传文件");
//2、创建FileItem工厂==>文件写入硬盘的作用
try {
DiskFileItemFactory factory = new DiskFileItemFactory();
//3、创建temp临时文件夹
String tempPath ="D:\\tomcat\\apache-tomcat-9.0.35-windows-x64\\apache-tomcat-9.0.35\\webapps\\librarySystem\\web\\net\\temp";
File tempFile = new File(tempPath);
factory.setRepository(tempFile);
//4、设置使用临时文件的边界值,大于该值,上传文件先保存在临时文件中,小于该值,则直接写入内存
//单位是字节
factory.setSizeThreshold(1024*1024*1);
//5、创建文件上传核心组件
// 调用ServletFileUpload.parseRequest方法解析request对象,得到一个保存了所有上传内容的List对象。
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding("utf-8");//可以解决文件名中文乱码
upload.setFileSizeMax(1024*1024*2);
String bNo="defaultBNo",bName="defaultBName";
//6、解析请求
List<FileItem> items =upload.parseRequest(request);
//7、遍历请求
for(FileItem item:items){
//普通表单项,上传名字,编号等普通信息的上i传
if(item.isFormField()){
String fileName = item.getFieldName();// name属性值
String fileValue = item.getString("utf-8");// name对应的value值
System.out.println(fileName + " -- " + fileValue);
if(fileName.equalsIgnoreCase("BNO")){
bNo = fileValue;
}
if(fileName.equalsIgnoreCase("BNAME")){
bName = fileValue;
}
}
else{//上传图片等
String fileName = item.getName();
System.out.println("上传文件名字:"+fileName);
String suffix = fileName.substring(fileName.lastIndexOf('.'));//获取文件类型
String newFileName = bNo+"_"+bName+suffix;
System.out.println(newFileName);
//获取输入流,其中有上传文件的内容
InputStream is = item.getInputStream();
//String path = this.getServletContext().getRealPath("/net/bookImage");//获得当前项目保存服务器地址,也就是web文件夹下
String path ="D:\\tomcat\\apache-tomcat-9.0.35-windows-x64\\apache-tomcat-9.0.35\\webapps\\librarySystem\\web\\net\\bookImage";
//文件夹内文件数目有上限,但是可以创建子目录
//获取当前系统时间
Calendar now = Calendar.getInstance();
int year = now.get(Calendar.YEAR);
int month = now.get(Calendar.MONTH)+1;
int day = now.get(Calendar.DAY_OF_MONTH);
path = path+"/"+year+"/"+month+"/"+day;
//若该目录不存在,直接创建新目录
File dirFile = new File(path);
if(!dirFile.exists()){
dirFile.mkdirs();
}
//创建目标文件,用来保存上传文件
File desFile = new File(path,newFileName);
//创建文件输出流
OutputStream os = new FileOutputStream(desFile);
//将输入流数据写入到输出流中
int len=-1;
byte[]buf = new byte[1024];
while((len=is.read(buf))!=-1){
os.write(buf,0,len);
}
//desFile.delete();//删除临时文件
os.close();//输出流
is.close();//输入流
//删除临时文件
item.delete();
}
}
} catch (FileUploadException e) {
e.printStackTrace();
}
}
}
来源:https://blog.csdn.net/weixin_44001521/article/details/106871216
标签:jsp,servlet,上传,文件
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
JS forEach跳出循环2种实现方法
2024-04-29 13:19:28
详解Mysql基础语法的使用
2024-01-28 07:50:05
python实现将excel文件转化成CSV格式
2021-10-16 05:23:50
Python生成随机数组的方法小结
2023-10-09 08:19:41
![](https://img.aspxhome.com/file/2023/1/114501_0s.jpg)
对DJango视图(views)和模版(templates)的使用详解
2021-05-30 00:37:51
使用OpenCV对运动员的姿势进行检测功能实现
2022-06-08 03:23:14
![](https://img.aspxhome.com/file/2023/2/68312_0s.png)
pytorch 预训练模型读取修改相关参数的填坑问题
2021-11-07 01:08:36
基于python3监控服务器状态进行邮件报警
2022-05-05 05:25:39
![](https://img.aspxhome.com/file/2023/3/97343_0s.png)
网站的视觉设计
2008-08-15 12:58:00
Oracle SQL中实现indexOf和lastIndexOf功能的思路及代码
2023-07-14 10:26:52
Golang加权轮询负载均衡的实现
2024-02-01 04:41:57
Java连接数据库oracle中文乱码解决方案
2024-01-19 02:48:10
![](https://img.aspxhome.com/file/2023/1/79231_0s.png)
python爬虫爬取淘宝商品比价(附淘宝反爬虫机制解决小办法)
2021-11-14 06:16:40
![](https://img.aspxhome.com/file/2023/2/75242_0s.jpg)
mysql中为用户设置密码的多种方法
2024-01-26 07:36:07
echarts柱状图坐标轴内容显示不全的两种解决办法
2023-09-06 03:57:34
![](https://img.aspxhome.com/file/2023/2/56122_0s.png)
深入理解Python虚拟机中字典(dict)的实现原理及源码剖析
2022-03-10 20:57:06
![](https://img.aspxhome.com/file/2023/5/79515_0s.png)
MySql采用GROUP_CONCAT合并多条数据显示的方法
2024-01-20 07:39:22
python网络爬虫实现个性化音乐播放器示例解析
2021-10-06 10:14:51
![](https://img.aspxhome.com/file/2023/3/112763_0s.png)
python日志通过不同的等级打印不同的颜色(示例代码)
2022-08-18 01:47:25
![](https://img.aspxhome.com/file/2023/5/124735_0s.png)
一条sql 语句搞定数据库分页
2009-03-21 18:32:00