JavaWeb:上传文件

1.建普通maven项目,或者maven项目,这里以普通maven为例,区别的jar包的导入方式啦

到中央仓库下载哦

2.结构

3.写fileservlet

复制代码
public class FileServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //判断上传的文件是普通的表单还是带文件的表单(以表单方式提交)
        if(!ServletFileUpload.isMultipartContent(req)){
            return;//普通表单,终止方法运行
        }

        //创建文件上传后的保存路径
        String uploadPath=this.getServletContext().getRealPath("/WEB-INF/upload");
        File uploadFile=new File(uploadPath);
        if(!uploadFile.exists()){
            uploadFile.mkdir();//不存在,就创建这个目录
        }

        //缓存,临时文件放置
        String tmpPath=this.getServletContext().getRealPath("/WEB-INF/tmp");
        File file=new File(tmpPath);
        if(!file.exists()){
            file.mkdir();//不存在,就创建这个目录(临时)
        }

        //处理上传的文件,一般通过流获取

        try{
            //创建DiskFileItemFactory对象,处理文件上传限制 大小 路径
            DiskFileItemFactory factory=getDiskFileItemFactory(file);
            //获取ServletFileUpload
            ServletFileUpload upload=getServletFileUpload(factory);
            //处理上传的文件
            String msg=uploadParseRequest(upload,req,uploadPath);
            //servlet请求转发
            req.setAttribute("msg",msg);
            req.getRequestDispatcher("info.jsp").forward(req,resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static String uploadParseRequest(ServletFileUpload upload, HttpServletRequest req, String uploadPath) throws FileUploadException, IOException {
        String msg="";
        List<FileItem>fileItems=upload.parseRequest(req);
        for(FileItem fileItem:fileItems){
            if(fileItem.isFormField()){
                String name=fileItem.getFieldName();
                String value=fileItem.getString("UTF-8");
                System.out.println(name+":"+value);
            }else {
                String uploadFileName=fileItem.getName();
                System.out.println("文件:"+uploadFileName);
                if(uploadFileName.trim().equals("")||uploadFileName==null){
                    continue;
                }
                //获取文件名(/),和后缀名(.)  /img.png
                String fileName=uploadFileName.substring(uploadFileName.lastIndexOf("/")+1);
                String fileExtName=uploadFileName.substring(uploadFileName.lastIndexOf(".")+1);

                System.out.println("文件消息:"+fileName+"类型"+fileExtName);
                //UUID 保证文件名唯一
                //UUID.randomUUID()随机生成一个通用码
                String uuidPath= UUID.randomUUID().toString();

                String realPath=uploadPath+"/"+uuidPath;
                File realPathFile=new File(realPath);
                if(!realPathFile.exists()){
                    realPathFile.mkdir();
                }
                //获取上传文件的流
                InputStream inputStream=fileItem.getInputStream();
                FileOutputStream fos=new FileOutputStream(realPath+"/"+fileName);

                //缓冲区
                byte[]buffer=new byte[1024*1024];
                //判断读取完成?
                int len=0;
                while ((len=inputStream.read(buffer))>0){
                    fos.write(buffer,0,len);
                }
                fos.close();
                inputStream.close();
                msg="success";
                fileItem.delete();
            }
        }
        return msg;
    }

    private static ServletFileUpload getServletFileUpload(DiskFileItemFactory factory) {
        ServletFileUpload upload=new ServletFileUpload(factory);
        //监听文件上传速度
        upload.setProgressListener(new ProgressListener() {
            @Override
            public void update(long l, long l1, int i) {
                System.out.println("总大小:"+l1+"已上传"+l);
            }
        });
        upload.setHeaderEncoding("UTF-8");
        upload.setFileSizeMax(1024*1024*10);
        //1024=1kb*1024=10M
        return upload;
    }

    private static DiskFileItemFactory getDiskFileItemFactory(File file) {
        DiskFileItemFactory factory=new DiskFileItemFactory();
        //设置缓冲区,文件大于缓冲区放到临时文件
        factory.setSizeThreshold(1024*1024);
        factory.setRepository(file);
        return factory;
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }
}

4.index.jsp

复制代码
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/upload.do" enctype="multipart/form-data" method="post">
    上传用户:<input type="text" name="username"><br>
    <p><input type="file" name="file1"></p>
    <p><input type="file" name="file1"></p>

    <p><input type="submit">||<input type="reset"></p>
</form>
</body>
</html>

5.info

复制代码
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<%--上传文件大小有限制:get--%>
${msg}
</body>
</html>
相关推荐
执子手 吹散苍茫茫烟波9 分钟前
leetcode415. 字符串相加
java·leetcode·字符串
小韩博15 分钟前
网络安全(Java语言)脚本 汇总(二)
java·安全·web安全
萤丰信息22 分钟前
技术赋能安全:智慧工地构建城市建设新防线
java·大数据·开发语言·人工智能·智慧城市·智慧工地
带刺的坐椅41 分钟前
Java MCP 的鉴权?好简单的啦
java·鉴权·mcp·solon-ai
Pocker_Spades_A1 小时前
飞算JavaAI家庭记账系统:从收支记录到财务分析的全流程管理方案
java·开发语言
33255_40857_280591 小时前
掌握分页艺术:MyBatis与MyBatis-Plus实战指南(10年Java亲授)
java·mybatis
Ashlee_code1 小时前
香港券商智能櫃台系統技術解決方案——融合跨境清算與AI風控,助力券商把握滬港雙市爆發機遇**
java·科技·金融·重构·架构·系统架构·php
蚰蜒螟1 小时前
Spring 和 Lettuce 源码分析 Redis 节点状态检查与失败重连的工作原理
java·redis·spring
小张快跑。1 小时前
Tomcat下载、安装及配置详细教程
java·服务器·tomcat
神仙别闹1 小时前
基于 JSP+Mysql实现MVC房屋租赁系统
java·mysql·mvc