混合表单文件上传到数据库(基于TOMCAT)

Posted nick7

tags:

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

在实际的开发中在实现文件上传的同时肯定还有其他信息需要保存到数据库,就像混合表单在上传完毕之后需要将提交的基本信息插入数据库。

在这个demo中需要用到技术图片这个架包来帮助实现

 

1.定义一个公共类实现文件上传(BaseServlet)

上传是一个公共的操作,可能在很多个servlet中都要涉及到上传,比如在Empservlet中要上传雇员的照片,在ManagerServlet中要上传管理员的照片,此时就需要将上传的操作定义到一个公共父类。

package com.sxt.mvcpro.servlet;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.text.ParseException;
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");
            smart.setMaxFileSize(1024 * 1024 * 1024 * 5);
            smart.setTotalMaxFileSize(1024 * 1024 * 1024 * 5 * 10);
            smart.upload();
            // 取得上传文件的路径信息
            String filepath = req.getServletContext().getRealPath("/" + this.getDir());
            File file = new File(filepath);
            if (!file.exists()) {
                file.mkdirs();
            }
            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)
            throws IllegalArgumentException, ParseException, UnsupportedEncodingException {
//    req.setCharacterEncoding("utf-8");
        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 = new String(this.smart.getRequest().getParameter(fname).getBytes("GBK"), "utf-8");
                }
                if (fvalue == null) {
                    continue;
                }
                System.out.println(fname+"==" + fvalue);
                if ("Double".equals(fs[i].getType().getSimpleName())) {
                    fs[i].set(t, Double.valueOf(fvalue));
                } else if ("Integer".equals(fs[i].getType().getSimpleName())) {
                    fs[i].set(t, Integer.parseInt(fvalue));
                } else if ("Date".equals(fs[i].getType().getSimpleName())) {// 2019-5-5
                    fs[i].set(t, new SimpleDateFormat("yyyy-MM-dd").parse(fvalue));
                } else {
                    fs[i].set(t, fvalue);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return t;
    }

    protected void removeFile(HttpServletRequest req, String fileName) {
        String filePath = req.getServletContext().getRealPath("/") + fileName;
        File file = new File(filePath);
        if (file.exists()) {
            file.delete();
        }
    }

//增加一个抽象方法子类必须实现(文件夹的名称交给子类决定)
    public abstract String getDir();
}

定义emp类:

package com.sxt.mvcpro.vo;

import java.io.Serializable;
import java.util.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 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;
    }

    @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 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;
    }

    public Emp(Integer empno, String ename, String job, Double sal, Date hiredate, Integer mgr, Double comm,
            Integer deptno, String img) {
        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;
        
    }

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



}

调整业务层父类(EmpServlet)

package com.sxt.mvcpro.servlet;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.sxt.mvcpro.dao.service.IEmpService;
import com.sxt.mvcpro.dao.service.impl.EmpServiceImpl;
import com.sxt.mvcpro.factory.ServiceFactory;
import com.sxt.mvcpro.vo.Emp;

@SuppressWarnings("serial")
@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 ("/regist".equals(pathInfo)) {
                this.regist(req, resp);
            }
                        } catch (Exception e) {
            e.printStackTrace();
        }
    }
public void regist(HttpServletRequest req, HttpServletResponse resp) throws UnsupportedEncodingException {
        super.saveFile(req, resp);
        // 将基本信息保存到数据库中
        Emp emp = null;
        try {
            emp = super.initObj(req, Emp.class);
            emp.setImg(super.newFileName);
            System.out.println(emp);
            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);
    }
@Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }

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

前端客户端输入界面代码:(newLogin.jsp)

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<base href="/Mvcpro/"/>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="emp/regist" method="POST" enctype="multipart/form-data">
<fieldset>
<legend>请注册</legend>
<br>编号:<input type="text" name="empno" value="7550"><br>
<br>姓名:<input type="text" name="ename" value="水电费"><br>
<br>职位:<input type="text" name="job" value="上单"><br>
<br>薪资:<input type="text" name="sal"value="20000"><br>
<br>领导编号:<input type="text" name="mgr"value="2343"><br>
<br>入职日期:<input type="text" name="hiredate"value="2019-07-04"><br>
<br>佣金:<input type="text" name="comm"value="1000"><br>
<br>部门编号:<input type="text" name="deptno"value="40"><br>
<br>&nbsp;&nbsp;&nbsp;片:<input type="file" name="img"><br>
<br><input type="submit" value="提交"><input type="reset" value="重置">
</fieldset>
</form>
</body>
</html>

前端客户端输出界面代码:(emp.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>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<base href="/MvcPro/"/>
</head>
<body>
    <h1>
            显示雇员的信息:${emp}
    </h1>
        <table border="1">
            <tr>
                <td>编号</td><td>姓名</td><td>职位</td><td>薪资</td><td>领导编号</td><td>入职日期</td><td>佣金</td><td>部门编号</td><td>照片</td>
            </tr>
            <tr>
                <td>${emp.empno}</td><td>${emp.ename}</td><td>${emp.job}</td><td>${emp.sal}</td><td>${emp.mgr}</td><td>${emp.hiredate}</td><td>${emp.comm}</td><td>${emp.deptno}</td><td><img src="${emp.img}"></td>
            </tr>
        </table>
</body>
</html>

调试效果图:

技术图片

 

技术图片

 

以上是关于混合表单文件上传到数据库(基于TOMCAT)的主要内容,如果未能解决你的问题,请参考以下文章

Struts2文件上传(基于表单的文件上传)

利用socket模拟http的混合表单上传(在一个请求中提交表单并上传多个文件)

strtus,formFile实现文件上传到tomcat服务器

springboot报错说 Failed to parse multipart servlet request; nested exception is java.io.IOException(代码片

9.16 基于form表单的文件上传实现 ContextType

MVC:如何将文件上传和其他表单字段发布到一个操作