spring MVC上传附件
spring mvc为我们封装了十分简单的上传附件的方法,以下通过一个例子学习。
1.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<!DOCTYPE>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>附件管理</title>
<!-- css文件 -->
<link rel="stylesheet" href="./static/bootstrap/css/bootstrap.min.css" />
<link rel="stylesheet"
href="./static/bootstrap/css/bootstrap-theme.min.css">
<link rel="stylesheet" href="./static/css/OtherCss/upload.css">
<!-- js文件 -->
<script type="text/javascript" src="./static/js/jquery-1.11.0.js"></script>
<script type="text/javascript"
src="./static/bootstrap/js/bootstrap.min.js"></script>
<script type="text/javascript" src="./static/js/OtherJs/upload.js"></script>
<!-- ajax form -->
<script type="text/javascript" src="./static/js/jquery.form.js"></script>
<script type="text/javascript" src="./static/js/ajaxfileupload.js"></script>
<script type="text/javascript"
src="./static/js/jquery-migrate-1.2.1.min.js"></script>
<script type="text/javascript">
var dialog = frameElement.dialog;
$(function() {
$("#submit1").click(function() {
if ($("#categoryName").val() == "") {
alert("请填写类别名称");
return false;
}
var ajax_option = {
url : "categoryAttSave",
type : "post",
dataType : "html",
success : function(data) {
if (data == 1) {
alert("成功");
} else {
alert("失败")
}
dialogClose();
}
}
$("#thisForm").ajaxSubmit(ajax_option);
});
}); //返回
function dialogClose() {
parent.g.loadData(parent.g.parms);
dialog.close();//关闭dialog
}
</script>
</head>
<body>
<form id="thisForm" method="post" action="categoryAttSave"
enctype="multipart/form-data">
<input type="hidden" name="categoryId" value="${category.categoryId}" />
<div class="container-fluid ">
<div class="col-xs-12">
<div class="panel-body ">
<div class="row">
<div class="col-xs-8 col-xs-offset-1 tipinfo"
style="padding-bottom: 10px">
<div class="input-group">
<h3>${category.categoryName}</h3>
</div>
</div>
</div>
<div class="row">
<div class="col-xs-8 col-xs-offset-1 tipinfo"
style="padding-bottom: 10px">
<div class="info_center" id="userface_x">
<div class="upload_face">
<div class="upload_btn">
<a type="button" class="upload_vl" id="upface_tt">选择您要上传的图片</a>
<p id="img_rq">仅支持JPG、GIF、PNG、JPEG、BMP格式,文件小于4M</p>
</div>
<div class="upface_img">
<c:choose>
<c:when test="${not empty category.categoryPic}">
<img id="preview" src="./${category.categoryPic}" />
</c:when>
<c:otherwise><img id="preview" src="./static/img/nopic.png" /></c:otherwise> </c:choose>
</div>
<div class="changeimg" style="display: none">
<input id="fileimg" type="file" name="upload" />
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-xs-5 col-xs-offset-5">
<button type="button" class="btn btn-default " onClick="dialogClose();">关闭</button>
<button type="button" class="btn btn-primary " id="submit1">
提交</button>
</div>
</div>
</div>
</div>
</div>
</form>
</body>
</html>
主要要注意的是form的地方必须加 enctype="multipart/form-data"这句话,还有就是<input id="fileimg" type="file" name="upload" />这句话。本实例用了一个js的上传插件。只是优化了上传的体验,不涉及到原理,所以此处不介绍相关内容。主要还是介绍如何实现上传。
2.后台代码
controller
@ResponseBody
@RequestMapping("categoryAttSave")
public String categoryAttSave(HttpServletRequest req, MultipartFile upload,
int categoryId) {
Integer result = categoryService.categoryAttSave(req, upload,
categoryId, uploadFile);
return result.toString();
}
Service
/**
* 附件上传并修改数据库
*
* @param req
* @param upload
* @param categoryId
* @param uploadFile
* @return
*/
public int categoryAttSave(HttpServletRequest req, MultipartFile upload,
int categoryId, String uploadFile) {
int result = 0;
String originalFileName = upload.getOriginalFilename();
String suffix = IOUtil.getFileSuffix(originalFileName);
String fileName = RandomUtil.getTimeStampPlusRand() + "." + suffix;
String realPath = req.getServletContext().getRealPath(uploadFile);
try {
upload.transferTo(new File(realPath + "/" + fileName));
// 数据库操作
TCategory category = baseDao.getT(
"TCategoryMapper.selectByPrimaryKey", categoryId);
String oldCategoryPic = category.getCategoryPic();
category.setCategoryPic(uploadFile + "/" + fileName);
baseDao.updateT("TCategoryMapper.updateCategoryPic", category);
// 删除原来的图片
IOUtil.deleteFile(req, oldCategoryPic);
result = 1;
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
其实主要是注意到传递过来的MultipartFile 名称,要与jsp里面的file名对应。还有就是我们需要用到request来获取附件最终存储的位置,所以传递了一个HttpServletRequest。上传就是这句话upload.transferTo(new File(realPath + "/" + fileName));很简单吧,如果我们自己写的话,就要通过输入流写入到file里了。而spring mvc只要一句简单的代码就实现了。
PS:上述代码还是有弊端的,当我们没有选定需要上传的图片而点击了上传的时候,它会报如下错误。
org.springframework.web.multipart.MultipartException: The current request is not a multipart request
大概意思就是,你这个请求并不是关于文件上传的请求。这是spring 替你检查了并直接报运行错误。
我们可以通过修改controller代码,替代spring 的检查,就可以规避这个错误了。
@ResponseBody
@RequestMapping("categoryAttSave")
public String categoryAttSave(HttpServletRequest req, int categoryId) {
MultipartFile upload = null;
if (req instanceof MultipartHttpServletRequest) {
upload = ((MultipartHttpServletRequest) req).getFile("upload");
}
Integer result = categoryService.categoryAttSave(req, upload, categoryId,
uploadFile);
return result.toString();
}
上述代码我们自己检查是不是关于文件上传的请求,就不会报错了。
spring MVC上传附件的更多相关文章
- Spring MVC上传文件
Spring MVC上传文件 1.Web.xml中加入 <servlet> <servlet-name>springmvc</servlet-name> <s ...
- Spring MVC 上传文件
Spring MVC上传文件需要如下步骤: 1.前台页面,form属性 method设置为post,enctype="multipart/form-data" input的typ ...
- Spring框架学习(8)spring mvc上传下载
内容源自:spring mvc上传下载 如下示例: 页面: web.xml: <?xml version="1.0" encoding="UTF-8"?& ...
- Spring MVC上传文件原理和resolveLazily说明
问题:使用Spring MVC上传大文件,发现从页面提交,到进入后台controller,时间很长.怀疑是文件上传完成后,才进入.由于在HTTP首部自定义了“Token”字段用于权限校验,Token的 ...
- 怎样解决asp.net.mvc上传附件超过长度问题?
最近,在做一个上传附件功能,但是文件超过4M,就报上传的文件超过长度问题
- spring mvc上传下载文件
前端jsp <%@ page language="java" contentType="text/html; charset=UTF-8" pageEnc ...
- Spring Mvc 上传文件Demo 实例
返得利购物. 淘宝.京东500家商城合作,包括全面的商城返利网.注冊就送5元,购物就有返利.随时提现. 同学们,新一轮的返利大潮正在慢慢靠近,让购物都认为自己在赚钱.购物,机票.游戏.酒店旅游,地方特 ...
- Spring MVC 上传、下载、显示图片
目录 1. 准备工作 1.1 数据库表准备 1.2 实体类 User 和 Mapper(DAO) 1.3 pom.xml 依赖包 1.4 SSM 框架的整合配置 2. 控制器 UserControll ...
- 解析Spring MVC上传文件
新建一个普通的maven工程 在pom.xml文件中引入相应的坐标 <?xml version="1.0" encoding="UTF-8"?> & ...
随机推荐
- 【2】构建一个SSM项目结构
初步思考一下这个项目的结构,由于是给一个比较老的公司做这个外包项目,服务器是搭建在windows操作系统上的Tomcat6.0,系统的JDK版本也是JDK1.6,都是比较旧. 数据库方面有专人负责,所 ...
- 基础教程:视图中的ASP.NET Core 2.0 MVC依赖注入
问题 如何在ASP.NET Core MVC Views中注入和使用服务. 解 更新 启动 类来为MVC添加服务和中间件. 添加一项服务 添加一个Controller,返回 ViewResult. 添 ...
- js的call() ,apply() 两种方法的区别和用法,最白话文的解释,让枯燥滚粗!
百度了一圈calll()函数和apply()函数,感觉还是糊里糊涂 正好我前几天刚又重新翻了一遍 那本 600多页 的圣经书,我习惯时不时的去打下基础,只是为了用来装逼,给人讲解....(我是有多蛋疼 ...
- Android Debug Bridge
Android Debug Bridge Introduction Android Debug Bridge (adb) is a versatile command line tool th ...
- github设置
ssh-key: https://help.github.com/articles/generating-ssh-keys http://segmentfault.com/q/101000000013 ...
- canvas图表(2) - 折线图
原文地址:canvas图表(2) - 折线图 话说这天气一冷啊, 就患懒癌, 就不想码代码, 就想着在床上舒舒服服看视频. 那顺便就看blender视频, 学习下3D建模, 如果学会了建3D模型, 那 ...
- C# 处理Word自动生成报告 二、数据源例子
还是以学生.语文.数学.分数为例吧, 感觉这个和helloworld都有一拼了. 造一张表如下, 整张报表就围绕这个表转圈了, 顺便说下就是名字如有雷同纯属巧合 新建个存储过程 ALTER PROCE ...
- JavaScript的简单继承实现案例
<html><body><script> //实现JavaScript继承的步骤: //1:写父类 //2:写子类 //3:用Object.create()来实现继 ...
- 邻里街坊 golang入坑系列
如果要追新或者怀旧,就点击https://andy-zhangtao.gitbooks.io/golang/content/ . 博客园里面的文章基本和gitbook上面是保持同步的. 这几天看了几集 ...
- 《Maven实战》 第7章 生命周期与插件
7.1什么是生命周期 软件开发人员每天都在对项目进行清理.编译.测试及部署,Maven生命周期是对所有构建过程进行抽象和统一,含项目的清理.初始化.编译.测试.打包.集成测试.验证.部署和站点生成等几 ...