10.基于Tomcat的SmartUplaod文件上传

Posted wangdh666

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了10.基于Tomcat的SmartUplaod文件上传相关的知识,希望对你有一定的参考价值。

  文件的上传是项目中常见的核心功能,比如在注册的时候可能在表单中要求用户提交照片等。此时就需要使用到文件的上传,本次课题以上传雇员的照片作为需求,但是在很多时候上传的的需求不仅仅是雇员,可能需要上传管理员头像等等,此时需要增加管理员的信息也可能要上传到servlet。文件上传的第三方工具有很多,我们这次使用的是SmartUpload组件。

  1.定义表单(login.jsp)

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <base href="/MvcPro/"/>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    <script type="text/javascript" src="js/jquery.min.js"></script>
</head>
<body>
    <form action="emp/regist" method="POST" enctype="multipart/form-data">
        <fieldset>
            <legend>请注册</legend>
             编号:<input type="text" value="74211" name="empno"/><br>
            <br>名字:<input type="text" value="smith" name="ename"><br>
            
            <br> 编号:<input type="text" value="7788" name="mgr"><br>
            <br> 薪资:<input type="text" value="9000.00" name="sal"><br>
            <br> 职位:<input type="text" value="Java" name="job"><br>
            <br> 佣金:<input type="text" value="1000.00" name="comm"><br>
            <br> 部门编号:<input type="text" value="10" name="deptno"><br>
            <br> 日期:<input type="text" value="2019-10-10" name="hiredate"><br>
            <br>&nbsp;&nbsp;&nbsp;片:<input type="file" name="img"><br>
            <br><input type="submit" value="提交"><input type="reset" value="重置">
        </fieldset>
    </form>
</body>
</html>

   2.定义公共类(BaseServlet.java)

  上传是一个公共的操作,可能在很多个servlet中都要涉及到上传,比如在EmpServlet中要上传雇员的照片,在ManageServlet中药上传管理员的照片,此时就需要将上传的操作定义到一个公共父类(可以定义为工具类)。由于上传信息里除了文件还需要提交其他信息,则表单数据提交需要转换成为二进制数据,需要在表单中添加enctype="multipart/form-data",此时可以实现文件的上传但是使用内置对象request获取表单的其他数据的时候就无法获取,此时直接借助SmarUplaod获取参数(需要导包)。

  

package com.sxt.mvcpro.controller;

import java.io.File;
import java.lang.reflect.Field;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.UUID;
import javax.servlet.ServletConfig;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.jspsmart.upload.SmartUpload;

@SuppressWarnings("serial")
public abstract class BaseServlet extends HttpServlet {

    SmartUpload smart = null;

    String newFileName = null;

    public void saveFile(HttpServletRequest req, HttpServletResponse resp) {

        smart = new SmartUpload();

        ServletConfig config = super.getServletConfig();

        // 照片处理
        try {
            // 初始化
            smart.initialize(config, req, resp);
            smart.setAllowedFilesList("jpg,png,gif,jpeg");
            smart.setMaxFileSize(1024 * 1024 * 1024 * 5);
            smart.setTotalMaxFileSize(1024 * 1024 * 1024 * 5 * 10);
            smart.upload();
            // 取得上传文件的路径信息
            String filepath = req.getServletContext().getRealPath("/"+getDir());
            File file = new File(filepath);
            if (!file.exists()) {
                file.mkdirs();
            }
            // 按照文件的原名称保存
            // smart.save(filePath)
            if (smart.getFiles().getFile(0).getSize()>0) {

                String ext = smart.getFiles().getFile(0).getFileExt();
                // 生成新的文件名
                String fileName = UUID.randomUUID().toString().replaceAll("-", "");
                newFileName = this.getDir() + fileName + "." + ext;
                // 保存文件(按照新文件名保存)
                smart.getFiles().getFile(0).saveAs(filepath + fileName + "." + ext);
            } else {
                throw new Exception("文件为空");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public <T> T initObj(HttpServletRequest req, Class<T> clz) {
        T t = null;
        try {
            t = clz.newInstance();
            Field[] fs = clz.getDeclaredFields();
            for (int i = 0; i < fs.length; i++) {
                fs[i].setAccessible(true);
                // 取得属性名
                String fname = fs[i].getName();
                // 从request内置对象中取得对应的值
                String fvalue = null;
                if (this.smart == null) {
                    fvalue = req.getParameter(fname);
                } else {
                    fvalue = this.smart.getRequest().getParameter(fname);
                }
                System.out.println(fvalue);
                if (fvalue == null) {
                    continue;
                }

                if ("Double".equals(fs[i].getType().getSimpleName())) {
                    System.out.println(fs[i].getType().getSimpleName());
                    fs[i].set(t, Double.valueOf(fvalue));
                } else if ("Integer".equals(fs[i].getType().getSimpleName())) {
                    fs[i].set(t, Integer.valueOf(fvalue));
                } else if ("Date".equals(fs[i].getType().getSimpleName())) {
                    fs[i].set(t, new Date(new SimpleDateFormat("yyyy-MM-dd").parse(fvalue).getTime()));
                } else {
                    fs[i].set(t, fvalue);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return t;
    }
    //    增加一个抽象方法 子类必须实现(文件夹的名称交给子类决定)
    public abstract String getDir();
}

  3.修改控制层(EmpServlet.java)

  在实际的开发中实现文件的上传的同时肯定还有其他信息需要保存到数据库。

package com.sxt.mvcpro.controller;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.concurrent.TimeUnit;
import javax.servlet.RequestDispatcher;
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 com.sxt.mvcpro.factory.ServiceFactory;
import com.sxt.mvcpro.service.IEmpService;
import com.sxt.mvcpro.service.impl.EmpServiceImpl;
import com.sxt.mvcpro.vo.Emp;

@WebServlet(urlPatterns= {"/emp/*","/dept/*"})
public class EmpServlet extends BaseServlet {
    
    //取得业务层实现类对象
    private IEmpService empservice=(IEmpService)ServiceFactory.getInstance(EmpServiceImpl.class);

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String pathInfo = req.getPathInfo();
        try {
            if ("/login".equals(pathInfo)) {
                this.login(req, resp);
            } else if ("/regist".equals(pathInfo)) {
                this.regist(req, resp);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        
    }
    
    public void regist(HttpServletRequest req, HttpServletResponse resp) throws UnsupportedEncodingException {
        req.setCharacterEncoding("UTF-8");
        //    super.saveFile(req,resp);
        //    将基本信息保存到数据库中
        super.saveFile(req, resp); 
        Emp emp = super.initObj(req, Emp.class);
        emp.setImg(super.newFileName);
        try {
            if (empservice.addEmp(emp)) {
                //    保存添加的雇员的信息
                req.setAttribute("emp", emp);
                req.getRequestDispatcher("/pages/emp.jsp").forward(req, resp);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(emp);
    }
    

    /**
     *     负责登陆的方法
     * @param req
     * @param resp
     * @throws Exception
     */
    public void login(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        String random = req.getParameter("code");
        String username = req.getParameter("username");
        String pwd = req.getParameter("pwd");
        if (req.getSession().getAttribute("rand").equals(random)) {
            if ("smith".equals(username)&&"1234".equals(pwd)) {
                //    保存用户信息到session之后跳转到欢迎页面
                req.getSession().setAttribute("name", username);
                resp.sendRedirect("/MvcPro/pages/welcome.jsp");
            } else {
                //    告知用户名和密码不正确(跳转到登录页面)
                req.setAttribute("msg", "用户名密码有误");
                req.getRequestDispatcher("/pages/login.jsp").forward(req, resp);
            }
        } else {
            //    跳转到登录页面告诉用户验证码不正确
            req.setAttribute("msg", "验证码错误");
            req.getRequestDispatcher("/pages/login.jsp").forward(req, resp);
        }
    }

    
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }

    @Override
    public String getDir() {
        return "empImgs/";
    }

    
    
}

  4.定义Emp类

package com.sxt.mvcpro.vo;

import java.io.Serializable;
import java.sql.Date;

public class Emp implements Serializable {
    private Integer empno;
    private String ename;
    private String job;
    private Double sal;
    private Date hiredate;
    private Integer mgr;
    private Double comm;
    private Integer deptno;
    private String img;
    
    public Emp() {
        super();
    }

    public Emp(Integer empno, String ename, String job, Double sal, Date hiredate, Integer mgr, Double comm,
            Integer deptno) {
        super();
        this.empno = empno;
        this.ename = ename;
        this.job = job;
        this.sal = sal;
        this.hiredate = hiredate;
        this.mgr = mgr;
        this.comm = comm;
        this.deptno = deptno;
    }
    
    public Integer getEmpno() {
        return empno;
    }
    public void setEmpno(Integer empno) {
        this.empno = empno;
    }
    public String getEname() {
        return ename;
    }
    public void setEname(String ename) {
        this.ename = ename;
    }
    public String getJob() {
        return job;
    }
    public void setJob(String job) {
        this.job = job;
    }
    public Double getSal() {
        return sal;
    }
    public void setSal(Double sal) {
        this.sal = sal;
    }
    public Date getHiredate() {
        return hiredate;
    }
    public void setHiredate(Date hiredate) {
        this.hiredate = hiredate;
    }
    public Integer getMgr() {
        return mgr;
    }
    public void setMgr(Integer mgr) {
        this.mgr = mgr;
    }
    public Double getComm() {
        return comm;
    }
    public void setComm(Double comm) {
        this.comm = comm;
    }
    public Integer getDeptno() {
        return deptno;
    }
    public void setDeptno(Integer deptno) {
        this.deptno = deptno;
    }

    public String getImg() {
        return img;
    }

    public void setImg(String img) {
        this.img = img;
    }

    @Override
    public String toString() {
        return "Emp [empno=" + empno + ", ename=" + ename + ", job=" + job + ", sal=" + sal + ", hiredate=" + hiredate
                + ", mgr=" + mgr + ", comm=" + comm + ", deptno=" + deptno + ", img=" + img + "]";
    }

    public Emp(Integer empno, String ename, String job, Double sal, Date hiredate, Integer mgr, Double comm,
            Integer deptno, String img) {
        super();
        this.empno = empno;
        this.ename = ename;
        this.job = job;
        this.sal = sal;
        this.hiredate = hiredate;
        this.mgr = mgr;
        this.comm = comm;
        this.deptno = deptno;
        this.img = img;
    }


}

  5.测试结果

技术图片

技术图片

以上是关于10.基于Tomcat的SmartUplaod文件上传的主要内容,如果未能解决你的问题,请参考以下文章

使用Tomcat搭建基于域名的虚拟机

部署基于Maven的war文件到Tomcat

Tomcat基于Servlet的无文件webshell的相关技术研究

基于linux服务器在Tomcat安装SSL证书

冰蝎改造之适配基于tomcat Filter的无文件webshell

冰蝎改造之适配基于tomcat Filter的无文件webshell