spring mvc 文件上传

                                                                          spring mvc 文件上传  

一、单文件上传

配置步骤:

步骤一、在配置文件中配置包扫描器(暂且这样配,会出问题,我们下面说解决方案)

 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:p="http://www.springframework.org/schema/p"xmlns:mvc="http://www.springframework.org/schema/mvc"xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsdhttp://www.springframework.org/schema/mvchttp://www.springframework.org/schema/mvc/spring-mvc.xsd "><!--让spring扫描包下所有的类,让标注spring注解的类生效  --><context:component-scan base-package="cn.hmy.controller"/></beans>

 

步骤二,定制我们的文件上传jsp页面

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html><head><base href="<%=basePath%>"><title>文件上传</title></head><body><form action="${pageContext.request.contextPath }/list.do" method="post" enctype="multipart/form-data"><h1>文件上传</h1>文件:<input type="file" name="fileUpLoad"/></br><input type="submit" value="上传"/>         </form></body>
</html>

步骤三、书写我们的处理器代码

package cn.hmy.controller;import java.io.File;
import java.io.IOException;import javax.servlet.http.HttpSession;import org.springframework.stereotype.Controller;import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;import cn.hmy.pojo.UserInfo;@Controller
public class MyController{//处理器方法@RequestMapping(value="/list.do")    public void doFirst(MultipartFile fileUpLoad,HttpSession session) throws Exception{//1.获取文件名称String filename = fileUpLoad.getOriginalFilename();//2.获取文件的前半部分路径String realPath = session.getServletContext().getRealPath("/images");//3.拼接成完整的路径File file=new File(realPath,filename);//4.保存文件
         fileUpLoad.transferTo(file); }        
}

此时我们启动服务器,进行代码上传,会报如下错误

 

解决方案:更改我们的spring-servlet.xml配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:p="http://www.springframework.org/schema/p"xmlns:mvc="http://www.springframework.org/schema/mvc"xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsdhttp://www.springframework.org/schema/mvchttp://www.springframework.org/schema/mvc/spring-mvc.xsd "><!--让spring扫描包下所有的类,让标注spring注解的类生效  --><context:component-scan base-package="cn.hmy.controller"/>
<!--配置复杂类型表达解析器-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"></bean></beans>

启动发现还是会报上述错误 

解决方案:配置注解驱动

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:p="http://www.springframework.org/schema/p"xmlns:mvc="http://www.springframework.org/schema/mvc"xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsdhttp://www.springframework.org/schema/mvchttp://www.springframework.org/schema/mvc/spring-mvc.xsd "><!--让spring扫描包下所有的类,让标注spring注解的类生效  --><context:component-scan base-package="cn.hmy.controller"/>
<!--配置复杂类型表达解析器--><bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"></bean>
<!--配置注解驱动-->
<mvc:annotation-driven/> </beans>

如果在上述配置文件中缺少复杂类型解析器,会报如下错误

 

 

在解决了以上错误后,我们会发现如果我们上传的文件中含有中文   会出现乱码现象

解决乱码

解决方案我们暂且提供以下两种方式

方案一、

方案二、在web.xml中配置

<filter><filter-name>characterEncoding</filter-name><filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class><init-param><param-name>encoding</param-name><param-value>utf-8</param-value></init-param><init-param><param-name>forceEncoding</param-name><param-value>true</param-value></init-param></filter><filter-mapping><filter-name>characterEncoding</filter-name><url-pattern>/*</url-pattern></filter-mapping>

 

如何控制文件上传大小

在spring-servlet.xml中配置如下

maxUploadSize为上传的总文件的大小 5M
maxInMemorySize为上传的单个文件的大小 1M
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"><property name="defaultEncoding" value="utf-8"></property><property name="maxUploadSize" value="5000000"></property><property name="maxInMemorySize" value="1000000"></property></bean>

如果超出所限制的大小  会报如下错误

 

 

控制文件上传的类型(通过后缀名进行控制)在处理器中进行判定

例如 只允许上传.jpg   .png   .gif为后缀的文件

package cn.hmy.controller;import java.io.File;
import java.io.IOException;import javax.servlet.http.HttpSession;import org.springframework.stereotype.Controller;import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;import cn.hmy.pojo.UserInfo;@Controller
public class MyController{//处理器方法@RequestMapping(value="/list.do")    public String doFirst(MultipartFile fileUpLoad,HttpSession session) throws Exception{//1.获取文件名称String filename = fileUpLoad.getOriginalFilename();//限定文件上传的类型if(filename.endsWith("jpg")||filename.endsWith("png")||filename.endsWith("gif")){//2.获取文件的前半部分路径String realPath = session.getServletContext().getRealPath("/images");//3.拼接成完整的路径File file=new File(realPath,filename);//4.保存文件
             fileUpLoad.transferTo(file); }else{System.out.println("不支持上传文件的类型");}return "/list.jsp";}        
}

 

 

 

如何判断用户没用选上传文件

 

 

多文件上传

步骤一、

spring-servlet.xml配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:p="http://www.springframework.org/schema/p"xmlns:mvc="http://www.springframework.org/schema/mvc"xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation="
        http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsdhttp://www.springframework.org/schema/mvchttp://www.springframework.org/schema/mvc/spring-mvc.xsd "><!--让spring扫描包下所有的类,让标注spring注解的类生效  --><context:component-scan base-package="cn.hmy.controller"/><bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"><property name="defaultEncoding" value="utf-8"></property><property name="maxUploadSize" value="5000000"></property><property name="maxInMemorySize" value="1000000"></property></bean><mvc:annotation-driven/>
</beans>

 

步骤二、准备多文件上传的jsp页面

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html><head><base href="<%=basePath%>"><title>文件上传</title></head><body><form action="${pageContext.request.contextPath }/list.do" method="post" enctype="multipart/form-data"><h1>文件上传</h1>文件1:<input type="file" name="fileUpLoad"/></br>文件2:<input type="file" name="fileUpLoad"/></br>文件3:<input type="file" name="fileUpLoad"/></br><input type="submit" value="上传"/>         </form></body>
</html>

步骤三、编写处理器的代码

 //多文件上传@RequestMapping(value="/list.do")    public String doFirst2(@RequestParam MultipartFile[] fileUpLoad,HttpSession session) throws Exception{for (MultipartFile item : fileUpLoad) {//1.获取文件名称String filename = item.getOriginalFilename();//限定文件上传的类型if(filename.endsWith("jpg")||filename.endsWith("png")||filename.endsWith("gif")){//2.获取文件的前半部分路径String realPath = session.getServletContext().getRealPath("/images");//3.拼接成完整的路径File file=new File(realPath,filename);//4.保存文件
                 item.transferTo(file); }else{System.out.println("不支持上传文件的类型");}}return "/list.jsp";}

注意:在处理器方法中一定要对参数进行校对使用注解@RequestParam校正参数

丢到  会报错

即可实现多文件上传

 

转载于:https://www.cnblogs.com/hmy-1365/p/6104501.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/371969.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

使用工厂模式解决设计问题

工厂设计模式是面向对象环境中最常用的模式之一。 再次来自“创意设计”模式类别&#xff0c;即有关对象创建的所有信息。 在某些情况下&#xff0c;对象的创建很复杂&#xff0c;可能需要某种程度的抽象&#xff0c;以便客户端代码无法意识到这些复杂性和内部实现细节。 在某些…

103. Binary Tree Zigzag Level Order Traversal

二刷。 BFS&#xff0c;基本习惯上用Iterative的做法来做&#xff0c;就是QUEUE。 /*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode(int x) { val x; }* }*/ public class Solution…

java多线程系列13 设计模式 Future 模式

Future 模式 类似于ajax请求 页面异步的进行后台请求 用户无需等待请求的结果 就可以继续浏览或者操作 核心就是&#xff1a;去除了主函数的等待时间&#xff0c;并使得原本需要等待的时间段可以用于处理其他业务逻辑 JDK内置实现Future模式演示一下 public class RealData im…

lodop转到其他html页面,Lodop实现打印功能

思路&#xff1a;1、在 html 页面引入 LodopFuncs.js 文件&#xff0c;并用 object 标签和 embed 标签获取 lodop 对象2、在 js 中获取 html 页面中的 object 和 embed 对象&#xff0c;并使用getLodop() 方法得到 lodop 对象3、实现打印功能&#xff0c;以下三步是必需的初始化…

完整的Web应用程序Tomcat JSF Primefaces JPA Hibernate –第3部分

Primefaces AutoComplete&#xff0c;JSF转换器 这篇文章从第一部分和第二部分继续。 JSF拥有Converter工具&#xff0c;可以帮助我们从用户视图中获取一些数据并将其转换为从数据库或缓存中加载的对象。 在“ com.converter”包中&#xff0c;创建以下类&#xff1a; packa…

html5首屏加载乐山暴雨,发布前端项目时因chunk-vendors过大导致首屏加载太慢,Vue Build时chunk-vendors的优化方案...

这个优化是两方面的&#xff0c;前端将文件打包成.gz文件&#xff0c;然后通过nginx的配置&#xff0c;让浏览器直接解析.gz文件。1、compression-webpack-plugin插件打包.gz文件安装插件npm install --save-dev compression-webpack-plugin或者yarn add compression-webpack-p…

width:100vh与min-height:calc(100vh + 51px)

vh:相对于视窗的高度&#xff0c;那么vw:则是相对于视窗的高度。 “视区”所指为浏览器内部的可视区域大小&#xff0c;即window.innerWidth/window.innerHeight大小&#xff0c;不包含任务栏标题栏以及底部工具栏的浏览器区域大小。 详细vh的用法&#xff0c;大家可以参考http…

XML配置文件中的Spring配置文件

我的上一个博客非常简单&#xff0c;因为它涵盖了我从Spring 3.0.x到Spring 3.1.x的轻松升级&#xff0c;最后我提到可以将Spring模式升级到3.1&#xff0c;以利用Spring的最新功能。 在今天的博客中&#xff0c;我将介绍这些功能中最酷的功能之一&#xff1a;Spring配置文件。…

交大计算机专业怎样,计算机专业高校实力排名,上海交大第五,清华第二,第一毫无争议...

原标题&#xff1a;计算机专业高校实力排名&#xff0c;上海交大第五&#xff0c;清华第二&#xff0c;第一毫无争议计算机专业在近几年可谓是“大热”&#xff0c;众多考生抢破头也想当码农&#xff0c;背后的原因其实不难理解。互联网时代的到来&#xff0c;计算机早已渗透到…

python_day7 绑定方法与非绑定方法

在类中定义函数如果 不加装饰器 则默认 为对象作为绑定方法 如果增加 classmethod 是 以 类 作为绑定方法 增加 classmethod 是 非绑定方法&#xff0c;就是不将函数 绑定 ##################### class Foo: def func(self): print(self) classmethod def func…

Spring Security使用Hibernate实现自定义UserDetails

大多数时候&#xff0c;我们将需要在Web应用程序中配置自己的安全访问角色。 这在Spring Security中很容易实现。 在本文中&#xff0c;我们将看到最简单的方法。 首先&#xff0c;我们将在数据库中需要以下表格&#xff1a; CREATE TABLE IF NOT EXISTS mydb.security_role (…

python之路-面向对象

编程范式 编程是 程序 员 用特定的语法数据结构算法组成的代码来告诉计算机如何执行任务的过程 &#xff0c; 一个程序是程序员为了得到一个任务结果而编写的一组指令的集合&#xff0c;正所谓条条大路通罗马&#xff0c;实现一个任务的方式有很多种不同的方式&#xff0c; 对这…

西安邮电大学计算机科学与技术有专硕吗,2020年西安邮电大学计算机学院考研拟录取名单及排名!...

20考研复试调剂群&#xff1a;4197552812020年西安邮电大学计算机学院硕士研究生招生复试成绩及综合排名各位考生&#xff1a;现将我院2020年硕士研究生招生复试成绩及综合排名公布(最终录取名单及新生学籍注册均以“全国硕士研究生招生信息公开平台”备案信息为准)&#xff0c…

用Java排序的五种有用方法

Java排序快速概述&#xff1a; 正常的列表&#xff1a; private static List VEGETABLES Arrays.asList("apple", "cocumbers", "blackberry");Collections.sort(VEGETABLES);output: apple, blackberry, cocumbers反向排序&#xff1a; pri…

[python]-数据科学库Numpy学习

一、Numpy简介&#xff1a; Python中用列表(list)保存一组值&#xff0c;可以用来当作数组使用&#xff0c;不过由于列表的元素可以是任何对象&#xff0c;因此列表中所保存的是对象的指针。这样为了保存一个简单的[1,2,3]&#xff0c;需要有3个指针和三个整数对象。对于数值运…

检测一个点, 是否在一个半圆之内的方法

demo: http://jsbin.com/lihiwigaso 需求: 一个圆分成分部分, 鼠标滑上不同的区域显示不同的颜色 思路: 先判断这个点是否在圆之内, 再判断是否在所在的三角形之内就可以了 所需要的全部源码: <!DOCTYPE html> <html> <head><meta charset"utf-8&quo…

计算机网络设备接地规范,网络机房防雷接地的四种方式及静电要求

编辑----河南新时代防雷由于计算机网络系统的核心设备都放置在网络机房内&#xff0c;因而网络机房防雷接地有了较高的环境要求&#xff0c;良好的接地系统是保证机房计算机及网络设备安全运行&#xff0c;以及工作人员人身安全的重要措施。直流地的接法通常采用网格地&#xf…

抓住尾部的StackOverFlowError

使用Java程序时可能要处理的一种更烦人的情况是StackOverFlowError&#xff0c;如果您有一个很好的可生产的测试用例&#xff0c;那么关于使用堆栈大小或设置条件断点/某种痕迹 。 但是&#xff0c;如果您有一个测试案例可能一次失败100次&#xff0c;或者像我的案例一样在AWTM…

Gunicorn配置部分的翻译

写在前面&#xff0c;虽然翻译得很烂&#xff0c;但也是我的劳动成果&#xff0c;转载请注明出处&#xff0c;谢谢。 Gunicorn版本号19.7.1 Gunicorn配置 概述 三种配置方式 优先级如下&#xff0c;越后的优先级越大 1.框架的设置&#xff08;现在只有paster在用这个&#xff0…

台式计算机风扇声音大怎么处理,如何解决电脑电源风扇声音大的问题?

现在的台式机一般用3到5年后&#xff0c;一些问题自然也就慢慢表现出来了。很多网友在使用电脑过程中都有电脑风扇声音大怎么办的问题&#xff0c;电脑风扇声音大就会让人觉得使用电脑很不舒服&#xff0c;怎么办好呢&#xff1f;出现重要的问题要如何解决好呢&#xff1f;现在…