servlet文件上传练习
程序员文章站
2022-03-10 19:22:21
package cn.alex.servlet;import org.apache.commons.fileupload.FileItem;import org.apache.commons.fileupload.FileItemFactory;import org.apache.commons.fileupload.FileUploadBase;import org.apache.commons.fileupload.FileUploadException;import org.apache....
1.关联图片上传的jar包(commons-io.jar、commons-fileupload.jar),数据库驱动包以及jstl相关的jar包(看你是否需要使用jstl)
2.定义表单,指定enctype属性以及提交方式为post,同时给定input类型为file的表单
3.解析提交的表单数据(request)
3.1.创建一个DiskFileItemFactory对象,作为ServletFileupload对象的工厂
3.2.创建ServletFileupload对象,通过该对象去解析request对象,返回一个FileItem集合对象
3.3.每个FileItem中包含的就是表单中对应的键值对
3.4.判断是否是文件对象
4.截取上传的文件的后缀与指定的后缀名进行匹配
5.给上传的文件起个新名字以保证名字不冲突(UUID、时间戳等等)
6.将该过名字的文件写入到指定的服务器的地址中
7.将文件的地址写入到数据库中进行存储
8.在前端的页面中显示上传的图片
package cn.alex.servlet;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadBase;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import javax.naming.SizeLimitExceededException;
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 javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
@WebServlet("/fileUploadServlet")
public class FileUploadServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
HttpSession session = req.getSession();
//使用一个可以读取磁盘的工厂对象
FileItemFactory factory = new DiskFileItemFactory();
//解析request对象,--我们需要一个ServletFileUpload对象,通过工厂生产一个文件上传对象
ServletFileUpload fileUpload = new ServletFileUpload(factory);
//得到ServletFileUpload对象,进行解析request
try {
//设置可上传的文件大小
fileUpload.setSizeMax(1024*1024);
//定义允许上传的文件后缀
String[] suffixArr = {".png",".jpg",".gif"};
List<FileItem> fileItemList = fileUpload.parseRequest(req);
//遍历FileItem集合,拿到每一个具体的FileItem,(包含一个键值对)
for (FileItem fileItem : fileItemList){
//需要判断当前FileItem是普通的表单数据还是文件上传对象
if(fileItem.isFormField()){//ture代表是表单字段,false代表是文件上传字段
String filedname = fileItem.getFieldName();
String filedVal = fileItem.getString();
}else {
String filedname = fileItem.getFieldName();
String filedVal = fileItem.getName();//getName是获取到上传文件的名字
//获取文件后缀,以最后一个.截取到末尾
int index = filedVal.lastIndexOf(".");
String suffix = filedVal.substring(index);
//判断后缀是否正确
//讲数组转换为集合使用集合中的contains方法判断
List<String> suffixList = Arrays.asList(suffixArr);
if(!suffixList.contains(suffix)){
session.setAttribute("picSuffix",suffixList);
resp.sendRedirect("index.jsp");
return;
}else {
//获取服务器中存储图片的文件夹地址
String realPath = req.getRealPath("/upload");
//将图片写入到指定的服务器地址中
File file = new File(realPath);
if(!file.exists()){
//如果文件不存在就创建下
file.mkdir();
}
//使用UUID生成一个随机的名字
String uuid = UUID.randomUUID().toString();
String fileName = uuid.replace("-","")+suffix;//将原生UUID的-替换为空字符
File writeFile = new File(realPath,fileName);
fileItem.write(writeFile);
//将图片的路径存储到数据库中
String sql = "insert into t_item(pic) values(?)";
DBUtil.curd(sql,fileName);
}
}
}
} catch (SizeLimitExceededException e){
session.setAttribute("sizeMsg","可上传的文件大小为:"+fileUpload.getSizeMax()/1024+"KB");
resp.sendRedirect("index.jsp");
} catch (FileUploadException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
本文地址:https://blog.csdn.net/qq_51576943/article/details/112252675