Spring MVC 文件上传简单示例(form、ajax方式 )
1、Form Upload
SpringMVC 中,文件的上传是通过 MultipartResolver 实现的,所以要实现上传,只要注册相应的 MultipartResolver 即可。
MultipartResolver 的实现类有两个:
CommonsMultipartResolver(需要 Apache 的 commons-fileupload 支持,它能在比较旧的 servlet 版本中使用,兼容性好)StandardServletMultipartResolver(不需要第三方 jar 包支持,它使用 servlet 内置的上传功能,但是只能在 Servlet 3 以上的版本使用
以 StandardServletMultipartResolver 为例,使用步骤如下。
首先,在 web.xml 中为 DispatcherServlet 配置 Multipart:
<servlet>
<servlet-name>mvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<multipart-config>
<max-file-size>5242880</max-file-size> <!-- 上传文件的大小限制,比如下面表示 5 M -->
<max-request-size>10485760</max-request-size> <!-- 一次表单提交中文件的大小限制,必须下面代表 10 M -->
<file-size-threshold>0</file-size-threshold> <!-- 多大的文件会被自动保存到硬盘上。0 代表所有 -->
</multipart-config>
</servlet>
其次,在spring中注册MultipartResolver:
<bean id="multipartResolver" class="org.springframework.web.multipart.support.StandardServletMultipartResolver"></bean>
然后就可以使用了。
前端代码:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>文件上传</title>
</head>
<body>
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="filename">
<input type="submit" value="提交">
</form>
</body>
</html>
后端代码:
package com.oukele.web; import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Pattern; @Controller
@RequestMapping(path = "/upload")
public class FileUploadController { @RequestMapping(path = "",method = RequestMethod.GET)
public String getPage(){
return "fileupload";
} @PostMapping
public String fileUpload(@RequestPart("filename")MultipartFile multipartFile, HttpServletRequest request) {
if( !multipartFile.isEmpty() ){
//验证文件是否为图片格式 && 文件大小不能超过 5M 1KB = 1024B
if( multipartFile.getContentType().contains("image/") && multipartFile.getSize() < 1024 * 1024 * 1024 * 5 ){
//图片的存储文件夹
String save = request.getServletContext().getRealPath("/images");
File file = new File(save);
if( !file.exists() ){
file.mkdirs();
}
//文件名
String fileName =multipartFile.getOriginalFilename().substring(0,multipartFile.getOriginalFilename().indexOf("."));
//上传文件的后缀
String zhui = multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().indexOf("."),multipartFile.getOriginalFilename().length());
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
//生成新的文件名
String fileNewName ="upload_"+fileName+"_"+simpleDateFormat.format(new Date())+zhui;
try {
//将此图片存储到images文件夹中
multipartFile.transferTo(new File(save+"\\"+fileNewName));
} catch (IOException e) {
e.printStackTrace();
} }else{
return "";
} } return "redirect:/upload";
} }
运行:

结果:

以ajax的方式,进行文件上传
前端代码:
<form action="#" method="post" enctype="multipart/form-data">
宠物图片: <input type="file" name="filename" id="update_pet_img" style="width: 70px">
</form>
<img style="margin-top: 50px" class="update_img" src="" width="100px" height="100px" alt="未上传图片">
js脚本
<script src="${pageContext.request.contextPath}/js/jquery-1.12.3.js"></script>
<script>
//修改区域-->,点击选择文件的时候实现自动上传图片。
$("#update_pet_img").change(function () {
var form = $(this).closest("form");
update_file_img(form);
});
//图片上传
function update_file_img(file) {
var formData = new FormData($(file)[0]);
//ajax请求
$.ajax({
type: "post",
url: "/imgUpload",
data: formData,
contentType: false,//告诉客户端不要设置Content-Type 请求头部
processData: false,//告诉客户端不处理过程数据
success: function (data) {//完成后的事件
$(".update_img").attr("src", data.img_src);//data.img_src得到图片的地址
},
error: function (error) {//出现错误时的事件
alert("出错啦。");
}
});
}
</script>
后端代码:(这里只是简单示例,练习可以适当减少)
package com.oukele.web; import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date; @Controller
@RequestMapping(path = "/imgUpload")
public class FileUpload { /*
* 宠物图片上传
* */
@PostMapping(produces = "application/json;charset=utf-8")
@ResponseBody
public String imgUpload(@RequestPart("filename") MultipartFile multipartFile, HttpServletRequest request, HttpServletResponse response){
if (multipartFile.isEmpty()) {
return "{\"error\":\"文件为空,错误格式\"}";
}
if (!multipartFile.getContentType().contains("image/")) {
return "{\"error\":\"只允许上传图片的文件\"}";
}
if (multipartFile.getSize() > 1024 * 1024 * 1024 * 5) {
return "{\"error\":\"图片大小不能超过5M\"}";
}
//图片的存储文件夹
String save = request.getServletContext().getRealPath("/images");
File file = new File(save);
if (!file.exists()) {
file.mkdirs();
}
String file1 = createFile(save, multipartFile); return file1;
}
//创建文件夹,格式为以日期文件名 比如 2018112 , 和 新的文件名,格式为 upload_文件名_日期.后缀名
public String createFile(String path, MultipartFile multipartFile) {
boolean flag = false;
String imgpath ="";
//创建文件夹
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
String dataFile = "/" + simpleDateFormat.format(new Date());
path += dataFile;
File file = new File(path);
if (!file.exists()) {
file.mkdirs();
}
//文件名
String fileName = multipartFile.getOriginalFilename().substring(0, multipartFile.getOriginalFilename().indexOf("."));
//上传文件的后缀
String zhui = multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().indexOf("."), multipartFile.getOriginalFilename().length());
//生成新的文件名
String fileNewName = "upload_" + fileName + "_" + simpleDateFormat.format(new Date()) + zhui;
try {
//将此图片存储到对应的文件夹中
multipartFile.transferTo(new File(path + "/" + fileNewName));
imgpath ="/images"+dataFile+"/"+ fileNewName;
flag = true;
} catch (Exception e) {
flag = false;
e.printStackTrace();
}
if( flag ){
return "{\"img_src\":\""+imgpath+"\"}";
} return "{\"error\":\"出现异常\"}";
}
}
演示:

Spring MVC 文件上传简单示例(form、ajax方式 )的更多相关文章
- 【Java Web开发学习】Spring MVC文件上传
[Java Web开发学习]Spring MVC文件上传 转载:https://www.cnblogs.com/yangchongxing/p/9290489.html 文件上传有两种实现方式,都比较 ...
- Spring MVC 笔记 —— Spring MVC 文件上传
文件上传 配置MultipartResolver <bean id="multipartResolver" class="org.springframework.w ...
- Spring MVC文件上传教程 commons-io/commons-uploadfile
Spring MVC文件上传教程 commons-io/commons-uploadfile 用到的依赖jar包: commons-fileupload 1.3.1 commons-io 2.4 基于 ...
- Spring mvc文件上传实现
Spring mvc文件上传实现 jsp页面客户端表单编写 三个要素: 1.表单项type="file" 2.表单的提交方式:post 3.表单的enctype属性是多部分表单形式 ...
- Spring mvc 文件上传到文件夹(转载+心得)
spring mvc(注解)上传文件的简单例子,这有几个需要注意的地方1.form的enctype=”multipart/form-data” 这个是上传文件必须的2.applicationConte ...
- spring mvc 文件上传 ajax 异步上传
异常代码: 1.the request doesn't contain a multipart/form-data or multipart/mixed stream, content type he ...
- Strut2 和Spring MVC 文件上传对比
在Java领域中,有两个常用的文件上传项目:一个是Apache组织Jakarta的Common-FileUpload组件 (http://commons.apache.org/proper/commo ...
- 【Spring】Spring MVC文件上传--整合bootstrap-fileinput和jQuery-File-Upload
前言 这里分享两个使用Spring MVC进行文件上传的简单示例, 分别整合bootstrap-fileinput 和 Jquery File Upload , 代码十分简单, 都是入门的示例,因此这 ...
- Spring MVC文件上传处理
以下示例显示如何在使用Spring Web MVC框架的表单中上传文件和处理.首先使用Eclipse IDE来创建一个WEB工程,实现一个上传文件并保存的功能.并按照以下步骤使用Spring Web ...
随机推荐
- 【Python开发】python读写文件,和设置文件的字符编码比如utf-8
一. python打开文件代码如下: f = open("d:\test.txt", "w") 说明: 第一个参数是文件名称,包括路径: 第二个参数是打开的模式 ...
- Xshell的使用以及常用命令
工具/原料 Xshell 方法/步骤 打开软件,点击新建,在主机哪里写入要访问的ip地址,名称随意 点击文件之后,再点击打开: 就可以看到刚才新建的会话了: 点击连接,就会显示下面的画面,输入用户名, ...
- 【Python】【demo实验3】【显示素数,显示两个数范围内的所有素数】
打印两个整数之间的所有素数: (使用平方根来判断 是否应停止验证该数值是否为素数) for i in range(956253526252,9956253526252): k = 1 if i == ...
- CF450A 【Jzzhu and Children】
普通的模拟题这题用一个队列容器来模拟队列元素是pair类型的,first用来存每个小朋友想要的糖数,second用来存小朋友的序号,然后开始模拟,模拟出口是当队列迟到等于1时就输出当前队列里小朋友的序 ...
- python_0基础开始_day06
第六节 1.小数据池 ==,is,id ==:查看等号两边的值是否一样 a = 9b = 9print(a == b) # 返回Truec = "dog"d = "dog ...
- Java Web开发技术教程入门-自定义标签
回顾: 昨天了解了JSP开发的两种模式Model1和Model2模式.Model1采用JSP+JavaBean技术开发Web应用,它比较适合小规模应用的开发,效率较高,易于实现.但由于在Model1中 ...
- Java重要类之LinkedList
一.ArrayList与LinkedList 基本概念:List是一个接口,Arraylist和LinkedList是它的两个实现类,只是实现的方式不一样.我在“单链表java实现”一文中已经对单链表 ...
- Nginx启动错误 Failed to read PID from file /run/nginx.pid 的处理方法
问题产生原因 因为 nginx 启动需要一点点时间,而 systemd 在 nginx 完成启动前就去读取 pid file 造成读取 pid 失败 解决方法 让 systemd 在执行 ExecSt ...
- Hive编程指南读书笔记(1):
1.Mapreduce是一种计算模型,将计算任务分割成多个可以在服务器集群中并行执行的任务,然后分散到一群家用的或者服务器级别的硬件机器上,从而降低成本并提供水平可伸缩性. 2.mapreduce的两 ...
- 重学JavaScript之匿名函数
1. 什么是匿名函数? 匿名函数就是没有名字的函数,有时候也称为< 拉姆达函数>.匿名函数是一种强大的令人难以置信的工具.如下: function a(a1, a2, a3) { // 函 ...