1、整合MVC实现文件上传
整合MVC实现文件上传
在实际的开发中在实现文件上传的同时肯定还有其他信息需要保存到数据库,文件上传完毕之后需要将提交的基本信息插入数据库,那么我们来实现这个操作。
整个MVC实现文件上传
1、拷贝之前的dao层和service
2、开发控制层(Controller)
3、调整dao层的父类(BaseController)
<%@ 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="testupload/regist" method="post" enctype="multipart/form-data">
    <fieldset>
        <legend>请注册</legend>
        name:<input type="text" name="ename" value="king"><br><br>
        sal:<input type="text" name="sal" value="9999.00"><br><br>
        job:<input type="text" name="job" value="manager"><br><br>
        comm:<input type="text" name="comm" value="3000.00"><br><br>
        deptno:<input type="text" name="deptno" value="10"><br><br>&nbsp;&nbsp;&nbsp;片:<input type="file" name="pic"><br><br>
        <input type="submit" value="提交"><br><br>
        <input type="reset" value="重置">
    </fieldset>
</form>

</body>
</html>
package cn.sxt.mvcpro.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.sxt.mvcpro.service.IEmpService;
import cn.sxt.mvcpro.service.impl.EmpServiceImpl;
import cn.sxt.mvcpro.servicefactory.ServiceFactory;
import cn.sxt.mvcpro.vo.Emp;

@SuppressWarnings("serial")
@WebServlet("/testupload/*")
public class TestUpload extends BaseServlet{
    @SuppressWarnings("static-access")
    IEmpService proxy = (IEmpService) new ServiceFactory().getInstance(EmpServiceImpl.class);
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
         String pathInfo = req.getPathInfo();
        if ("/regist".equals(pathInfo)) {
            this.regist(req,resp);
        }
    }
    private void regist(HttpServletRequest req, HttpServletResponse resp) {
//        System.out.println(req.getParameter("username"));
        saveFile(req, resp);
        Emp emp = initObj(req, Emp.class);
        System.out.println(emp);
        System.out.println(proxy.addEmp(emp));
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
    @Override
    public String getDir() {
        return "empImg/";
    }
}

 

package cn.sxt.mvcpro.controller;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.UUID;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jspsmart.upload.SmartUpload;
import com.jspsmart.upload.SmartUploadException;

@SuppressWarnings("serial")
public abstract class BaseServlet extends HttpServlet {
    SmartUpload smart = null;
    String newFileName = null;

    public void saveFile(HttpServletRequest req, HttpServletResponse resp) {
        try {
            // 1.实例化上传的工具对象(jspSmartUpload.jar)
            smart = new SmartUpload();
            // 2.取得config内置对象
            ServletConfig config = this.getServletConfig();
            // 3.初始化smart
            smart.initialize(config, req, resp);
            // 4.设置相关参数
            smart.setAllowedFilesList("jpg,png,gif");
            // smart.setDeniedFilesList("mp4");
            smart.setMaxFileSize(1024 * 1024 * 1024 * 3);
            smart.setTotalMaxFileSize(1024 * 1024 * 1024 * 3 * 10);
            // 5.实现上传(将文件放到内存,还没有到 磁盘)
            smart.upload();
            // 6.取得项目部署路径
            String savePath = req.getServletContext().getRealPath("/"+this.getDir());
            System.out.println(savePath);
            File file = new File(savePath);
            if (!file.exists()) {
                file.mkdirs();
            }
            // 按照文件的原名保存--》 smart.save(savePath);
            // 7.为文件重命名保存(避免覆盖)
            String ext = smart.getFiles().getFile(0).getFileExt();// 取得文件扩展名
            System.out.println(smart.getFiles());
            System.out.println(smart.getFiles().getFile(0));
            System.out.println(smart.getFiles().getFile(0).getFileExt());
            newFileName = UUID.randomUUID() + "." + ext;
            smart.getFiles().getFile(0).saveAs(savePath + newFileName.replaceAll("-", ""));
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (SmartUploadException e) {
            e.printStackTrace();
        }

    }

    public <T> T initObj(HttpServletRequest req, Class<T> clz) {
        T t = null;
        try {
            t = clz.newInstance();
            Field[] fields = clz.getDeclaredFields();
            for (Field f : fields) {
                f.setAccessible(true);
                String fname = f.getName();
//                System.out.println(fname + "================");
                String fvalue = null;
                if (this.smart == null) {
                    fvalue = req.getParameter(fname);
//                    System.out.println(fvalue + ">>>>>>>>>>>>");
                } else {
                    fvalue = smart.getRequest().getParameter(fname);
//                    System.out.println(fvalue + "<<<<<<<<<<<<<<<");
                }
                if (fvalue == null) {
                    continue;
                }
                if ("Double".equals(f.getType().getSimpleName())) {
                    f.set(t, Double.valueOf(fvalue));
                } else if ("Integer".equals(f.getType().getSimpleName())) {
                    f.set(t, Integer.valueOf(fvalue));
                } else if ("Date".equals(f.getType().getSimpleName())) {
                    try {
                        f.set(t, new SimpleDateFormat("yyyy-MM-dd").parse(fvalue));
                    } catch (IllegalArgumentException | ParseException e) {
                        e.printStackTrace();
                    }
                } else {
                    f.set(t, fvalue);
                }
            }
        } catch (InstantiationException | IllegalAccessException e) {
            e.printStackTrace();
        }
        return t;
    }

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

 

posted on 2019-04-23 20:51  随风|||  阅读(137)  评论(0编辑  收藏  举报