Spring上传文件,图片,以及常见的问题
1. 在工程依赖库下添加文件上传jar包
commons-fileupload-1.2.2.jar
commons-io-2.4.jar
2.在springMVC配置文件中配置视图解析multipartResolver
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="5000000" />
<property name="defaultEncoding" value="UTF-8" />
</bean>
这里有个问题需要注意一下,Bean 的id必须为multipartResolver,因为在项目初始化的时候,Spring容器会通过这个id来进行注入,下面是Spring源码:
public static final String MULTIPART_RESOLVER_BEAN_NAME = "multipartResolver";
/** MultipartResolver used by this servlet */
private MultipartResolver multipartResolver;
/*
省略一大堆代码
*/
/**
* Initialize the MultipartResolver used by this class.
* <p>If no bean is defined with the given name in the BeanFactory for this namespace,
* no multipart handling is provided.
*/
private void initMultipartResolver(ApplicationContext context) {
try {
this.multipartResolver = context.getBean(MULTIPART_RESOLVER_BEAN_NAME, MultipartResolver.class);
if (logger.isDebugEnabled()) {
logger.debug("Using MultipartResolver [" + this.multipartResolver + "]");
}
}
catch (NoSuchBeanDefinitionException ex) {
// Default is no multipart resolver.
this.multipartResolver = null;
if (logger.isDebugEnabled()) {
logger.debug("Unable to locate MultipartResolver with name '" + MULTIPART_RESOLVER_BEAN_NAME +
"': no multipart request handling provided");
}
}
}
接下来,我们测试一下如果写错之后会报什么错误

上面只是DEBUG, 查看源码就会知道会DEBUG输出这一句,
下面是具体报的错误:预期的MultipartHttpServletRequest:是否配置了MultipartResolver?

下面依次是jsp代码和后台实现上传的java代码:
<form id="userForm" name="userForm" method="post"
action="${pageContext.request.contextPath }/user/useraddsave.html"
enctype="multipart/form-data">
<div>
<label for="a_idPicPath">证件照:</label> <input type="file"
name="a_idPicPath" id="a_idPicPath" /> <font color="red"></font>
</div>
<div class="providerAddBtn">
<input type="button" name="add" id="add" value="保存"> <input
type="button" id="back" name="back" value="返回">
</div>
</form>
//保存新增用户信息
@RequestMapping(value="/useraddsave.html",method=RequestMethod.POST)
public String addUserSave(User user,HttpServletRequest request,@RequestParam(value="a_idPicPath",required=false) MultipartFile multipartFile){ if(!multipartFile.isEmpty()){
String path = "/statics"+File.separator+"upload"; //文件或者图片上传到的位置
String oldName = multipartFile.getOriginalFilename(); //上传的文件名
String prefix = FilenameUtils.getExtension(oldName); //文件的后缀名
int maxSize =5000000;
if(multipartFile.getSize()<maxSize){
if(prefix.equalsIgnoreCase("jpg")|| prefix.equalsIgnoreCase("png")){
String fileName = System.currentTimeMillis()+RandomUtils.nextInt(1000000)+"_Personal."+prefix; // 为避免文件名一样随机生成的文件名保存在服务器
File targetFile = new File(path,fileName);
if(!targetFile.exists()){
targetFile.mkdirs();
}
try {
multipartFile.transferTo(targetFile); //开始上传
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
request.setAttribute("uploadFileError", "上傳出現異常,上傳失敗");
}
String idPicPath= path+File.separator+fileName;
user.setIdPicPath(idPicPath);
user.setCreationDate(new Date());
userService.add(user);
return "redirect:/user/userlist.html";
} else {
request.setAttribute("uploadFileError", "文件格式錯誤,上傳失敗");
}
} else {
request.setAttribute("uploadFileError", "文件太大,上傳失敗");
}
}
return "useradd";//新增失败返回到useradd.jsp
}
方法需要添加参数 @RequestParam(value="a_idPicPath",required=false) MultipartFile multipartFile
The end......
Spring上传文件,图片,以及常见的问题的更多相关文章
- spring上传文件
在使用spring上传文件的时候,使用的文件接收参数类型为 org.springframework.web.multipart.MultipartFile 如果该参数没有指定@RequestParam ...
- ASP.NET、JAVA跨服务器远程上传文件(图片)的相关解决方案整合
一.图片提交例: A端--提交图片 protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { string u ...
- PHP socket上传文件图片
最近了解了下下socket方面的东西,想做一个socket上传文件的例子. 在网上搜了搜代码执行后,图片数据传输了一半,图片的下半部分是灰色的.然后就自己仿着搜来的代码和php.net 中socket ...
- 基于spring-boot的web应用,ckeditor上传文件图片文件
说来惭愧,这个应用调试,折腾了我一整天,google了很多帖子,才算整明白,今天在这里做个记录和分享吧,也作为自己后续的参考! 第一步,ckeditor(本博文论及的ckeditor版本4.5.6)的 ...
- spring 上传文件文件的一个例子,
/** * 类名称:UploadTest 类描述:创建人:zhang 创建时间:2015年3月13日 下午4:20:57 修改人:zhang * 修改时间:2015年3月13日 下午4:20:57 修 ...
- Spring 上传文件
最近碰到一个上传文件的需求,其实之前也做过但是都是search->copy 没有细究过,这次纯手工. 先看一下需要依赖的包: <dependency> <groupId> ...
- 通过PHP CURL模拟请求上传文件|图片。
现在有一个需求就是在自己的服务器上传图片到其他服务器上面,过程:客户端上传图片->存放到本地服务器->再转发到第三方服务器; 由于前端Ajax受限制,只能通过服务器做转发了. 在PHP中通 ...
- elementUI 上传文件图片大小加了限制后 仍然上传了
https://blog.csdn.net/chanlingmai5374/article/details/80558444 看了这位老哥的说法 在看看文档 才发现自己没认真看文档 <el-u ...
- 【2】通过Ajax方式上传文件(图片),使用FormData进行Ajax请求
HTML: <form id= "uploadForm"> <p >指定文件名: <input type="text" name= ...
随机推荐
- 学生问的一道javascript面试题[来自腾讯]
function Parent() { this.a = 1; this.b = [1, 2, this.a]; this.c = { demo: 5 }; this.show = function ...
- SSRF漏洞学习
SSRF SSRF(Server-Side Request Forgery:服务器端请求伪造) 是一种由攻击者构造形成由服务端发起请求的一个安全漏洞.一般情况下,SSRF攻击的目标是从外网无法访问的内 ...
- Spring Boot整合Dubbo使用及开发笔记
一.概述: Spring Dubbo是我开发的一个基于spring-boot和dubbo,目的是使用Spring boot的风格来使用dubbo.(即可以了解Spring boot的启动过程又可以学习 ...
- ajax执行顺序问题
在一个函数里,执行顺序是先传所有的值到指定url,然后再返回所有的success 解决方法:将ajax改成异步 aysnc:false
- IDE eclipse PyDev插件安装
Python安装成功后,即要配置开发环境,这里选用Eclipse, 在Eclipse中安装PyDev插件,有多种方法,这里介绍最最常用的两种. 1)使用Eclipse安装插件,打开eclipse,进入 ...
- shell 编程之 if...else case...esac
shell的条件判断语句有三种 if...fi 语句 if...else...fi 语句 if...elif...fi 语句 例子: a=10; b=20; if [ $a -gt %b ] t ...
- ThinkSNS+ 基于 Laravel master 分支,从 1 到 0,再到 0.1
什么是 ThinkSNS+ 09 年,由北京的团队开发了 ThinkSNS 涉足社交开源行业.这么多年累计不少客户.2014-2016,两年都在维护和开发之前基于 TP 的 ThinkSNS , 慢慢 ...
- UWP:使用Behavior实现FlipView简单缩放效果
先上效果图 首先安装Behavior SDK:在Nuget中搜索安装 Microsoft.Xaml.Behaviors.Uwp.Managed . 然后新建类,AnimationFlipViewBeh ...
- re模块和正则表达式
re模块 讲正题之前我们先来看一个例子:https://reg.jd.com/reg/person?ReturnUrl=https%3A//www.jd.com/ 这是京东的注册页面,打开页面我们就看 ...
- MySQL中的完整性约束
对于已经创建好的表,虽然字段的数据类型决定所能存储的数据类型,但是表中所存储的数据是否合法并没有检查. MySQL支持的完整性约束: NOT NULL 约束字段的值不能 ...