SpringMVC 通过commons-fileupload实现文件上传
配置
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="https://jakarta.ee/xml/ns/jakartaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee https://jakarta.ee/xml/ns/jakartaee/web-app_5_0.xsd"
version="5.0">
<!--注册DispatcherServlet-->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
SpringMVC配置文件 applicationContext.xml
上传文件的核心配置类:CommonsMultipartResolver,注意id="multipartResolver"不要写错
<?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:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--配置自动扫描controller包-->
<context:component-scan base-package="com.pro.controller"/>
<!--配置静态资源过滤-->
<mvc:default-servlet-handler/>
<!--配置注解驱动-->
<mvc:annotation-driven/>
<!--配置视图解析器-->
<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!--前缀-->
<property name="prefix" value="/WEB-INF/jsp/"/>
<!--后缀-->
<property name="suffix" value=".jsp"/>
</bean>
<!--SpringMVC文件上传配置-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!--设置请求的编码格式, 必须和pageEncoding的属性一致, 以便正确读取表单的值, 默认为ISO-8859-1-->
<property name="defaultEncoding" value="utf-8"/>
<!--上传文件的大小限制, 单位为字节 (10485760 = 10M)-->
<property name="maxUploadSize" value="10485760"/>
<property name="maxInMemorySize" value="40960"/>
</bean>
</beans>
文件上传 Controller
上传实现一
package com.pro.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
@RestController
public class FileController {
/*
* 采用file.transferTo 来保存上传的文件
*/
@RequestMapping("/upload2")
public Map fileUpload2(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws IOException {
//上传路径保存设置
String path = request.getServletContext().getRealPath("/upload");
File realPath = new File(path);
if (!realPath.exists()){
realPath.mkdir();
}
//上传文件地址
System.out.println("上传文件保存地址 --> "+realPath);
//通过CommonsMultipartFile的方法直接写文件(注意这个时候)
file.transferTo(new File(realPath +"/"+ file.getOriginalFilename()));
Map<Object, Object> hashMap = new HashMap<>();
hashMap.put("code", 0);
hashMap.put("msg", "上传成功");
return hashMap;
}
}
上传实现二
这里的文件名称没有使用 UUID组合名称 为了方便测试
package com.pro.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
@RestController
public class FileController {
// @RequestParam("file") 将 name=file 控件得到的文件封装成 CommonsMultipartFile 对象
// 批量上传把 CommonsMultipartFile 改为数组即可
@RequestMapping("/upload")
public String upload(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws IOException {
// 获取文件名称
String uploadFileName = file.getOriginalFilename();
// 如果文件名为空, 直接返回首页
if ("".equals(uploadFileName)) {
return "file upload error";
}
System.out.println("上传文件名 --> " + uploadFileName);
// 设置文件的保存位置
String path = request.getServletContext().getRealPath("/upload");
// 判断路径是否存在
File realPath = new File(path);
if (!realPath.exists()) {
// 如果不存在就创建
realPath.mkdir();
}
System.out.println("文件保存路径 --> " + realPath);
// 获取文件输入流
InputStream is = file.getInputStream();
// 获取文件输出流
FileOutputStream os = new FileOutputStream(new File(realPath, uploadFileName));
// 缓冲区读写文件
byte[] buffer = new byte[1024];
int len;
while ((len = is.read(buffer)) != -1) {
os.write(buffer, 0, len);
os.flush();
}
// 关闭流
os.close();
is.close();
return "file upload success";
}
}
测试
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
</head>
<body>
<form enctype="multipart/form-data" action="${pageContext.request.contextPath}/upload2" method="post">
<input type="file" name="file">
<input type="submit" value="上传实现一">
</form>
<form enctype="multipart/form-data" action="${pageContext.request.contextPath}/upload" method="post">
<input type="file" name="file">
<input type="submit" value="上传实现二">
</form>
</body>
</html>
依赖
核心依赖就是 commons-fileupload
<!--导入依赖-->
<dependencies>
<!--单元测试-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
</dependency>
<!--spring-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.0.RELEASE</version>
</dependency>
<!--文件上传-->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
<!--servlet-api导入高版本的-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
</dependency>
<!--jsp-->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
</dependency>
<!--jstl表达式-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
SpringMVC 通过commons-fileupload实现文件上传的更多相关文章
- Apache Commons fileUpload实现文件上传之一
需要两个jar包: commons-fileupload.jar Commons IO的jar包(本文使用commons-io-2.4.jar) 利用Servlet来实现文件上传. package ...
- Spring MVC使用commons fileupload实现文件上传功能
通过Maven建立Spring MVC项目,引入了Spring相关jar依赖. 1.为了使用commons fileupload组件,需要在pom.xml中添加依赖: <properties&g ...
- Apache Commons FileUpload 实现文件上传
Commons FileUpload简介 Apache Commons是一个专注于可重用Java组件开发的 Apache 项目.Apache Commons项目由三个部分组成: 1.Commons P ...
- Apache Commons FileUpload实现文件上传
一.Apache Commons-FileUpload简介 Apache Commons是一个专注于可重用Java组件的所有方面的 Apache 项目. Apache Commons项目由三个部分组成 ...
- SpringMVC(四)-- springmvc的系统学习之文件上传、ajax&json处理
资源:尚学堂 邹波 springmvc框架视频 一.文件上传 1.步骤: (1)导入jar包 commons-fileupload,commons-io (2)在springmvc的配置文件中配置解析 ...
- 分享知识-快乐自己:SpringMvc中的单多文件上传及文件下载
摘要:SpringMvc中的单多文件上传及文件下载:(以下是核心代码(拿过去直接能用)不谢) <!--设置文件上传需要的jar--> <dependency> <grou ...
- zt对于C#中的FileUpload解决文件上传大小限制的问题设置
对于C#中的FileUpload解决文件上传大小限制的问题设置 您可能没意识到,但对于可以使用该技术上载的文件的大小存在限制.默认情况下,使用 FileUpload 控件上载到服务器的文件最大为 4M ...
- 使用fileupload实现文件上传
一. fileupload组件工作原理 先来张图片, 帮助大家理解 fileupload核心API 1. DiskFileItemFactory构造器1) DiskFileItemFactory() ...
- springMVC数据校验与单文件上传
spring表单标签: <fr:from/> 渲染表单元素 <fr:input/>输入框组件 <fr:password/>密码框组件标签 & ...
- SpringMVC ajax技术无刷新文件上传下载删除示例
参考 Spring MVC中上传文件实例 SpringMVC结合ajaxfileupload.js实现ajax无刷新文件上传 Spring MVC 文件上传下载 (FileOperateUtil.ja ...
随机推荐
- windows下用pip安装库,出现Command "python setup.py egg_info"错误信息
转自:http://blog.csdn.net/u011092188/article/details/64123561 解决方案: python -m pip install --upgrade -- ...
- Linux音频编程--使用ALSA库播放wav文件
在UBUNTU系统上使用alsa库完成了对外播放的wav文件的案例. 案例代码: /** *test.c * *注意:这个例子在Ubuntu 12.04.1环境下编译运行成功. * */ #inclu ...
- 循序渐进VUE+Element 前端应用开发(32)--- 手机短信动态码登陆处理
在一些系统中,有时候用户忘记密码,可以通过向自己手机发送动态验证码的方式实现系统登录功能.本篇随笔介绍如何结合后端ABP框架的短信发送和缓存模块的处理,实现手机短信动态码登陆处理. 一般的登录方式,分 ...
- 腾讯IOT安卓开发初探
目录 腾讯IOT 安卓开发初探 Tecent IOT 开发平台的使用 新建项目 创建产品 添加自定义功能 设备开发 微信小程序配置 面板配置 新建设备 使用设备 安卓开发 前置配置 data.json ...
- JAVA_基础反射创建运行时类的对象
通过反射去创建对应的运行时类的对象 newInstance():调用此方法,创建对应的运行时类的对象.内部调用的是空参的构造器. 要想此方法正常的创建运行时类的对象,要求: 1.运行时类必须提供空参构 ...
- fastjson复现项目代码
详情请见:https://www.cnblogs.com/yunmuq/p/14268028.html 以下是代码 // FastjsonDemo.java package test; import ...
- dhcp分发地址以及静态路由设置
路由器R1配置: system-view [Huawei]sysname R1 [R1]user-interface console 0 [R1-ui-console0]idle-timeout 0 ...
- LeetCode897. 递增顺序查找树
题目 法一.自己 1 class Solution { 2 public: 3 vector<int>res; 4 TreeNode* increasingBST(TreeNode* ro ...
- 基于kubernetes实现coredns的及验证
CoreDNS: k8s内部的DNS ,用于对pod对service做记录的,好让其他的pod做访问 这里不用做过多的阐述 官方kube-dns现在已经没有在维护了,从Kubernetes 1.11 ...
- 【开源】我和 JAP(JA Plus) 的故事
JA Plus 故事 程序员的故事如此简单之绕不过去的开源情结 我们准备做一件伟大的事,也可以说是一件真真正正普惠的事. 絮 是的,你没有看错,就是"絮"而非"序&quo ...