基于Spring MVC实现文件上传:
-
使用commons-fileupload实现上传文件到本地目录。
-
实现上传文件到阿里云OSS和从阿里云OSS下载文件到本地。
1. 创建项目
选择Maven快速构建web项目,项目名称为case14-springmvc03。
2. 配置Maven依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.wfit.springmvc</groupId><artifactId>springmvc02</artifactId><version>1.0-SNAPSHOT</version><packaging>war</packaging><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><maven.compiler.source>1.8</maven.compiler.source><maven.compiler.target>1.8</maven.compiler.target></properties><dependencies><!--spring mvc--><dependency><groupId>org.springframework</groupId><artifactId>spring-webmvc</artifactId><version>5.3.8</version></dependency><!--servlet--><dependency><groupId>javax.servlet</groupId><artifactId>javax.servlet-api</artifactId><version>3.1.0</version><scope>provided</scope></dependency><!--fileupload--><dependency><groupId>commons-fileupload</groupId><artifactId>commons-fileupload</artifactId><version>1.4</version></dependency><!--aliyun-sdk-oss--><dependency><groupId>com.aliyun.oss</groupId><artifactId>aliyun-sdk-oss</artifactId><version>3.15.1</version></dependency></dependencies>
</project>
3. 创建Spring MVC配置文件
src.main.resources目录下创建spring-mvc.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: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"><!--开启注解--><context:component-scan base-package="com.wfit"/><!--启用mvc--><mvc:annotation-driven></mvc:annotation-driven><!--文件上传解析器--><bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"><!--设置上传大小 最大1M--><property name="maxUploadSize" value="1048576"/></bean>
</beans>
4. 配置web.xml
<!DOCTYPE web-app PUBLIC"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN""http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app><!--解决POST中文乱码问题 过滤器--><filter><filter-name>encodingFilter</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></filter><filter-mapping><filter-name>encodingFilter</filter-name><url-pattern>/*</url-pattern></filter-mapping><!--配置前端控制器DispatcherServlet--><servlet><servlet-name>dispatcherServlet</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><!--加载SpringMVC文件--><init-param><param-name>contextConfigLocation</param-name><param-value>classpath:spring-mvc.xml</param-value></init-param><!--启动容器时加载servlet--><load-on-startup>1</load-on-startup></servlet><servlet-mapping><servlet-name>dispatcherServlet</servlet-name><!--表示拦截所有请求--><url-pattern>/</url-pattern></servlet-mapping>
</web-app>
5. 创建UploadController类
在src.main.java.com.wfit.upload目录下创建UploadController类,实现文件上传。
@Controller
@RequestMapping("/upload")
public class UploadController {/*** 文件上传* @param file* @return*/@PostMapping("/upload")@ResponseBodypublic String upload(MultipartFile file) throws IOException {//验证文件是否为空if(ObjectUtils.isEmpty(file) || file.getSize() <=0){return "file is empty";}//创建上传文件位置File uploadDir = new File("D:\\upload");//获取文件名String fileName = file.getOriginalFilename();//创建目标文件File desFile = new File(uploadDir,fileName);//执行上传操作file.transferTo(desFile);return "success";}
}
6. 创建OssController类
在src.main.java.com.wfit.upload目录下创建OssController类,实现上传文件到阿里云OSS和从阿里云OSS下载文件到本地。
@Controller
@RequestMapping("/oss")
public class OssController {//访问OSS的域名private static String endpoint = "oss-cn-beijing.aliyuncs.com";//accessKeyId和accessKeySecret是OSS的访问密钥private static String accessKeyId = "<yourAccessKeyId>";private static String accessKeySecret = "<yourAccessKeySecret>";//Bucket用来管理所存储Object的存储空间private static String bucketName = "<yourBucketName>";//目标文件private static String objectName = "upload/123.txt";/*** 上传文件到阿里云OSS* @return*/@PostMapping("/upload")@ResponseBodypublic String upload(MultipartFile file) throws IOException {//验证文件是否为空if(ObjectUtils.isEmpty(file) || file.getSize() <=0){return "file is empty";}InputStream inputStream = file.getInputStream();// 创建OSSClient实例OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);try {// 创建PutObjectRequest对象PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, inputStream);// 设置该属性可以返回response。如果不设置,则返回的response为空putObjectRequest.setProcess("true");// 创建PutObject请求PutObjectResult result = ossClient.putObject(putObjectRequest);// 如果上传成功,则返回200System.out.println(result.getResponse().getStatusCode());} catch (Exception e) {System.out.println("Error Message:" + e.getMessage());} return "success";}/*** 下载阿里云文件到本地* @return*/@PostMapping("/download")@ResponseBodypublic String download(String objName,String path) throws IOException {//下载目录String pathName = "download/123.txt";// 创建OSSClient实例OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);try {// 下载Object到本地文件,并保存到指定的本地路径中ossClient.getObject(new GetObjectRequest(bucketName, objectName), new File(pathName));} catch (Exception e) {System.out.println("Error Message:" + e.getMessage());}return "success";}
}
7. Postman执行上传文件到本地目录