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"?> & ...
随机推荐
- python 小白(无编程基础,无计算机基础)的开发之路 辅助知识1 with...as
这个语法是用来代替传统的try...finally语法的. with EXPRESSION [ as VARIABLE] WITH-BLOCK 基本思想是with所求值的对象必须有一个__enter_ ...
- 一:MySQL数据库的性能的影响分析及其优化
MySQL数据库的性能的影响分析及其优化 MySQL数据库的性能的影响 一. 服务器的硬件的限制 二. 服务器所使用的操作系统 三. 服务器的所配置的参数设置不同 四. 数据库存储引擎的选择 五. 数 ...
- [转载] 详细讲解Hadoop中的简单数据库HBase
转载自http://www.csdn.net/article/2010-11-28/282614 数据模型 HBase数据库使用了和Bigtable非常相似的数据模型.用户在表格里存储许多数据行.每个 ...
- 其他信息: ORA-01400: 无法将 NULL 插入
这个错误其实就是oracle数据库的某列约束为 not null,但在插入值的时候插入了控制,无论是null和"",它都识别为空 有两种方法: 1.修改数据库字段约束为允许为空 2 ...
- 自己动手修改Robotium代码(下)
public void takeScreenshot(){ View decorView = viewFetcher.getRecentDecorView(viewFetcher.getWindo ...
- 如何实现 Service 伸缩?- 每天5分钟玩转 Docker 容器技术(97)
上一节部署了只有一个副本的 Service,不过对于 web 服务,我们通常会运行多个实例.这样可以负载均衡,同时也能提供高可用. swarm 要实现这个目标非常简单,增加 service 的副本数就 ...
- Grafana+Prometheus系统监控之SpringBoot
前言 前一段时间使用SpringBoot创建了一个webhook项目,由于近期项目中也使用了不少SpringBoot相关的项目,趁着周末,配置一下使用prometheus监控微服务Springboot ...
- LSF-SCNN:一种基于 CNN 的短文本表达模型及相似度计算的全新优化模型
欢迎大家前往腾讯云社区,获取更多腾讯海量技术实践干货哦~ 本篇文章是我在读期间,对自然语言处理中的文本相似度问题研究取得的一点小成果.如果你对自然语言处理 (natural language proc ...
- C语言之scanf
#include<stdio.h>int main(){int num;int a,b,c,result,d,result1;scanf("int%d",&nu ...
- 【epub.js|翻译|原创】开源中间件epub.js的使用及其中文文档
epub是最流行的电子书规范之一,网络上对于Java Web有不少合适的方法来解析和呈现,但是关于epub.js的介绍比较少(尽管github上已经2K星了),更多的是概念性的内容,如: epub.j ...