这里笔者介绍利用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

最新文章

  1. Leetcode 75. Sort Colors
  2. 无废话SharePoint入门教程五[创建SharePoint页面布局]
  3. jquery 之 Deferred 使用与实现
  4. Web前端性能优化教程05:网站样式和脚本
  5. iOS官方Sample大全
  6. 普林斯顿结构 VS 哈佛结构
  7. iOS7: 如何获取不变的UDID
  8. magic-encoding
  9. Rehat 5.8下oracle11g安装
  10. ubuntu LVM
  11. Message Authentication Code
  12. tomcat服务器端口冲突问题的解决
  13. JSP的内置对象以及作用域。
  14. jQuery学习之旅 Item1 选择器【一】
  15. [PHP] 频率限制类
  16. Java高阶语法---Volatile
  17. day15 Python风湿理论之函数即变量
  18. YY老总李学凌给记者们的几句话
  19. PAT甲1077 Kuchiguse【字符串】【暴力】【Hash】【二分】
  20. HDU 1232:畅通工程(并查集模板)

热门文章

  1. 7.4 Javascript:表单验证-揭开正則表達式的面纱
  2. ZooKeeper启动报错 JAVA_HOME is incorrectly set
  3. OpenWRT下实现Portal认证(WEB认证)
  4. iOS编程(双语版) - 视图 - 手工代码(不使用向导)创建视图
  5. Maven项目同时使用lib下的Jar包
  6. Mysql查询数据库表结构以及字段类型并展示
  7. Servlet简介与生命周期
  8. 在Ubuntu上安装pyenv 相关问题Common build problems
  9. psql 查询表大小
  10. [nQSError: 37001]Could not connect to the Oracle BI Server Instance