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();
}

整合MVC实现文件上传的更多相关文章

  1. Spring MVC实现文件上传

    基础准备: Spring MVC为文件上传提供了直接支持,这种支持来自于MultipartResolver.Spring使用Jakarta Commons FileUpload技术实现了一个Multi ...

  2. MVC之文件上传1

    MVC之文件上传 前言 这一节我们来讲讲在MVC中如何进行文件的上传,我们逐步深入,一起来看看. Upload File(一) 我们在默认创建的项目中的Home控制器下添加如下: public Act ...

  3. Asp.net mvc 大文件上传 断点续传

    Asp.net mvc 大文件上传 断点续传 进度条   概述 项目中需要一个上传200M-500M的文件大小的功能,需要断点续传.上传性能稳定.突破asp.net上传限制.一开始看到51CTO上的这 ...

  4. Spring MVC的文件上传

    1.文件上传 文件上传是项目开发中常用的功能.为了能上传文件,必须将表单的method设置为POST,并将enctype设置为multipart/form-data.只有在这种情况下,浏览器才会把用户 ...

  5. Spring MVC的文件上传和下载

    简介: Spring MVC为文件上传提供了直接的支持,这种支持使用即插即用的MultipartResolver实现的.Spring MVC 使用Apache Commons FileUpload技术 ...

  6. 【Spring学习笔记-MVC-13】Spring MVC之文件上传

    作者:ssslinppp       1. 摘要 Spring MVC为文件上传提供了最直接的支持,这种支持是通过即插即用的MultipartResolve实现的.Spring使用Jakarta Co ...

  7. MVC图片上传、浏览、删除 ASP.NET MVC之文件上传【一】(八) ASP.NET MVC 图片上传到服务器

    MVC图片上传.浏览.删除   1.存储配置信息 在web.config中,添加配置信息节点 <appSettings> <add key="UploadPath" ...

  8. spring mvc ajaxfileupload文件上传返回json下载问题

    问题:使用spring mvc ajaxfileupload 文件上传在ie8下会提示json下载问题 解决方案如下: 服务器代码: @RequestMapping(value = "/ad ...

  9. 0062 Spring MVC的文件上传与下载--MultipartFile--ResponseEntity

    文件上传功能在网页中见的太多了,比如上传照片作为头像.上传Excel文档导入数据等 先写个上传文件的html <!DOCTYPE html> <html> <head&g ...

随机推荐

  1. 安装ns2.34,802.11p的各种包的时候遇到问题

    安装教程:http://blog.sina.com.cn/s/blog_6735526a0102w1zs.html 802.11p补丁包:https://download.csdn.net/downl ...

  2. zabbix免客户端监控网站URL

    1.我们需要在zabbix服务器端(这台服务器需要能正常上网)同时安装zabbix-agent客户端,使其正常监控zabbix服务器 2.创建web监测 点击web监测 创建web监测 3.配置异常报 ...

  3. 阿里云-免费SSL证书申请及验证步骤

    1.登录阿里云管理控制台,在搜索栏输入ssl,选择第一个SSL证书控制台回车即可 2.点击右上角的购买证书 3.选择购买最后一个品牌 4.选择增强型OV SSL 5.选中后会自动弹出免费型DV SSL ...

  4. 使用 AppScan 进行扫描

    针对大型网站的扫描,我们按照戴明环 PDCA 的方法论来进行规划和讨论,建议 AppScan 使用步骤:计划(Plan).执行(Do).检查(check).分析(Analysis and Action ...

  5. 使用korofileheader插件vs code添加文件头注释和函数注释

    korofileheadervs code添加文件头注释和函数注释1.extensions搜索fileheader,安装koroFileHeader2.设置:edit=>perference=& ...

  6. conda使用技巧

    https://www.cnblogs.com/Sinte-Beuve/p/8597429.html https://www.cnblogs.com/xiaotongtt/p/8909844.html ...

  7. TR069网管测试华为ITMS平台(内部测试使用)

    声明:本篇华为ITMS平台仅用于学习和测试使用,如果需要商用,请购买正版软件! 原创作品,转载请注明出处,严禁非法转载或者用于商业目的! email:40879506@qq.com 一. 准备软件 V ...

  8. Python之print()函数

    1. 输出字符串 >>> str = 'Hello World' >>> print (str) Hello World 2. 格式化输出整数 支持参数格式化 &g ...

  9. 线程中AutoResetEvent与ManualResetEvent的区别

    线程之间的通信是通过发信号来进行沟通的.. ManualResetEvent发送Set信后后,需要手动Reset恢复初始状态.而对于AutoResetEvent来说,当发送完毕Set信号后,会自动Re ...

  10. RDLC报表系列--------初级报表

    前面记录下了很多平时开发遇到的问题,RLDC之前也是不会,只会水晶报表,后来也慢慢的也上手了.把这些记录下来,以后用的着 1.打开VS添加新建项,选择Reporting,选择报表,后缀名为RLDC的名 ...