这里笔者介绍利用SpringMVC上传图片的操作。

步骤

1.  引入jar文件

不仅需要导入开发SpringMVC相关的包,还需要导入 commons-fileupload-1.2.1.jar 和 commons-io-1.3.2.jar 包

2.  配置applicationContext.xml

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"></bean>

3.  编写html文件:

需要注意: 提交文件, 只能使用POST方式, 并且要指定enctype="multipart/form-data"
例如:

    <form action="file.do" method="POST" enctype="multipart/form-data">
请选择您要上传的文件:<br><br>
<input type="file" name="file"/><br>
<input type="submit"/>
</form>

4.  编写接收上传文件的Controller了  ,接收的文件的类型: MultipartFile

例如:

@RequestMapping("/file.do")
public String fileUpload(MultipartFile file){
//上传的文件: file
System.out.println("上传的文件名称为:"+file.getOriginalFilename());
return "result";
}

Demo

下面是一个接受上传图片的Demo,该Demo能够把用户上传的图片存储到部署项目的根目录下面。那么如何查看自己项目的根目录:点击 项目->.metadata->.plugins->org.eclipse.wst.server.core->tmp0->wtpwebapps ,在里面就可以看到部署的项目了。

jsp文件:

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
文件上传成功:${imagePath }
</body>
</html>

fileUploadOk.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
文件过大, 请上传1M以内的图片
</body>
</html>

fileUploadError.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>上传错误</title>
</head>
<body>
请上传图片类型~ .jpg .png .jpeg
</body>
</html>

error.jsp

文件上传表单:

<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>文件上传</title>
</head>
<body>
<form action="fileupload.do" method="POST" enctype="multipart/form-data">
<input type="file" name="file"/>
<input type="submit" value="提交"/>
</form>
</body>
</html>

fileUpload.jsp

dispatcherServlet-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:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd"> <!--指定注解扫描包-->
<context:component-scan base-package="cn"></context:component-scan>
<!--开启注解扫描-->
<mvc:annotation-driven/> <!--配置视图-->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass">
<value>org.springframework.web.servlet.view.InternalResourceView</value>
</property>
<!--jsp存放的目录-->
<property name="prefix">
<value></value>
</property>
<!--jsp文件的后缀-->
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"></bean>
</beans>

dispatcherServlet-servlet.xml

web.xml文件:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
<display-name>SpringMVC_FileUpLoad</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
</web-app>

web.xml

FileController.java控制器文件:

package cn.xdl.Controller;

import java.io.File;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile; @Controller
public class FileController { @RequestMapping("/fileupload.do")
public String fileUpload(MultipartFile file,HttpServletResponse response,HttpServletRequest request){
//判断文件的类型------------------//
String fileName = file.getOriginalFilename();
if(fileName.endsWith(".jpeg")||fileName.endsWith(".png")||fileName.endsWith(".jpg")){
//判断文件的类型------------------//
//上传的是图片
//图片大小的判断---------------------//
System.out.println("上传的图片的大小为: "+ file.getSize());
int size = 1024*1024;
//文件大小是否过大 , true表示过大
boolean flag = false;
if(file.getSize()<Integer.MAX_VALUE){
int fileSize = (int) file.getSize();
if(fileSize>size){
//文件过大
flag = true;
}else{
//大小合适
flag = false;
}
}else{
//文件大小过大
flag = true;
}
//文件过大 则响应错误页面
if(flag){
//文件过大
return "redirect:fileUploadError.jsp";
}else{
//文件大小正常 ,将文件存储到项目当前运行目录下
String dirPath = request.getServletContext().getRealPath("/");//获取当前项目运行时的目录 // 获取到的目录: webContent目录
System.out.println(dirPath);
File imgDir = new File(dirPath+"/images");
if(!imgDir.exists())
imgDir.mkdirs();
try {
fileName = fileName.replace(".", ",");
String newFileName = System.currentTimeMillis()+"."+(fileName.split(",")[fileName.split(",").length-1]);
file.transferTo(new File(imgDir,newFileName ));
request.getSession().setAttribute("imagePath", "<a href='images/"+newFileName+"'>点击查看</a>");
return "redirect:fileUploadOk.jsp";
} catch (Exception e) {
e.printStackTrace();
}
}
}else{
//上传的是其他文件
System.out.println("上传的不是图片");
} return "error";
}
}

FileController.java

【Spring】SpringMVC之上传文件的更多相关文章

  1. 《SpringMVC从入门到放肆》十五、SpringMVC之上传文件

    上一篇我们学习了数据分组校验,已经可以灵活的在项目中进行数据校验了,今天来学习SpringMVC的上传文件功能.相对来说SpringMVC的上传功能,还是比较简单的. 一.添加依赖 <depen ...

  2. Spring MVC上传文件

    Spring MVC上传文件 1.Web.xml中加入 <servlet> <servlet-name>springmvc</servlet-name> <s ...

  3. SpringMVC上传文件

    SpringMVC中上传文件还是比较方便的,Spring内置了一些上传文件的支持类,不需要复杂的操作即可上传文件. 文件上传需要两个jar支持,一个是commons-fileupload.jar和co ...

  4. 2. SpringMVC 上传文件操作

    1.创建java web项目:SpringMVCUploadDownFile 2.在项目的WebRoot下的WEB-INF的lib包下添加如下jar文件 com.springsource.com.mc ...

  5. Spring MVC上传文件原理和resolveLazily说明

    问题:使用Spring MVC上传大文件,发现从页面提交,到进入后台controller,时间很长.怀疑是文件上传完成后,才进入.由于在HTTP首部自定义了“Token”字段用于权限校验,Token的 ...

  6. springmvc上传文件,抄别人的

    SpringMVC中的文件上传 分类: SpringMVC 2012-05-17 12:55 26426人阅读 评论(13) 收藏 举报 stringuserinputclassencoding 这是 ...

  7. Spring MVC 上传文件

    Spring MVC上传文件需要如下步骤: 1.前台页面,form属性 method设置为post,enctype="multipart/form-data"  input的typ ...

  8. springboot(十七):使用Spring Boot上传文件

    上传文件是互联网中常常应用的场景之一,最典型的情况就是上传头像等,今天就带着带着大家做一个Spring Boot上传文件的小案例. 1.pom包配置 我们使用Spring Boot最新版本1.5.9. ...

  9. (转)Spring Boot(十七):使用 Spring Boot 上传文件

    http://www.ityouknow.com/springboot/2018/01/12/spring-boot-upload-file.html 上传文件是互联网中常常应用的场景之一,最典型的情 ...

随机推荐

  1. Ubuntu16.04中Docker的卸载

    1:利用sudo apt-get remove docker 进行卸载提示如下,docker未按照所以不能卸载 2:再次查看docker版本,依然还在 3:原因是安装的时候安装的是docker-ce版 ...

  2. vSCode打开文件老覆盖原窗口

    https://segmentfault.com/q/1010000006131199?_ea=1023522 设置中搜preview,改为false

  3. Node js : Best way to define entity class

      If you start to use a DB like mongo, you might be better off creating objects with mongoose but th ...

  4. linux设置开机同步时间

    在/etc/init.d/下新建zhjdate脚本,添加如下内容: #!/bin/bash# chkconfig: 345 63 37#chkconfig:345 63 37 (数字345是指在运行级 ...

  5. (C++)字符串分割

    题目: 如何对C++中输入的字符串进行分割呢?如“I am a student”,去除空格后分割成为“I”,“am”, “a”, “student”四个单词 思路: 直接参考代码 代码: void s ...

  6. ORACLE 执行计划

    有关oracle 执行计划几个不错的连接 执行计划的一些概念介绍:http://database.51cto.com/art/200611/34273.htm执行计划的例子:http://www.or ...

  7. JAVA 报错exe4j中this executable was created with an evaluation 怎么办

    如果使用未破解注册的exe4j打包JAR文件为EXE,运行EXE的时候就会出现下面的提示   打开exe4j软件,Change License或者是输入序列号,然后用注册机算一个注册码即可  

  8. Selenium2(WebDriver)总结(三)---元素定位方法

    元素定位的重要性不言而喻,如果定位不到元素谈何操作元素呢,webdrvier提供了很多种元素定位方法,如ID,Name,xpath,css,tagname等. 例如需要定位如下元素: <inpu ...

  9. VS2015使用小技巧

    VS2015常用快捷键 1.回到上一个光标位置/前进到下一个光标位置 1)回到上一个光标位置:使用组合键“Ctrl + -”; 2)前进到下一个光标位置:“Ctrl + Shift + - ” 2.复 ...

  10. Android开发经典笔试面试题汇总(持续更新中)

    1.我们都知道Handler是线程与Activity通信的桥梁,假设线程处理不当.你的机器就会变得非常慢,那么线程销毁的方法是:(A) A. onDestroy() B. onClear() C. o ...