基于Spring MVC实现文件上传:
- 使用commons-fileupload实现上传文件到本地目录。
- 实现上传文件到阿里云OSS和从阿里云OSS下载文件到本地。
1. 创建项目
选择Maven快速构建web项目,项目名称为case14-springmvc03。
2. 配置Maven依赖
<projectxmlns="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。
<beansxmlns="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-scanbase-package="com.wfit"/><!--启用mvc--><mvc:annotation-driven></mvc:annotation-driven><!--文件上传解析器--><beanid="multipartResolver"class="org.springframework.web.multipart.commons.CommonsMultipartResolver"><!--设置上传大小 最大1M--><propertyname="maxUploadSize"value="1048576"/></bean></beans>
4. 配置web.xml
<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类,实现文件上传。
"/upload") (publicclassUploadController { /*** 文件上传* @param file* @return*/"/upload") (publicStringupload(MultipartFilefile) throwsIOException { //验证文件是否为空if(ObjectUtils.isEmpty(file) ||file.getSize() <=0){ return"file is empty"; } //创建上传文件位置FileuploadDir=newFile("D:\\upload"); //获取文件名StringfileName=file.getOriginalFilename(); //创建目标文件FiledesFile=newFile(uploadDir,fileName); //执行上传操作file.transferTo(desFile); return"success"; } }
6. 创建OssController类
在src.main.java.com.wfit.upload目录下创建OssController类,实现上传文件到阿里云OSS和从阿里云OSS下载文件到本地。
"/oss") (publicclassOssController { //访问OSS的域名privatestaticStringendpoint="oss-cn-beijing.aliyuncs.com"; //accessKeyId和accessKeySecret是OSS的访问密钥privatestaticStringaccessKeyId="<yourAccessKeyId>"; privatestaticStringaccessKeySecret="<yourAccessKeySecret>"; //Bucket用来管理所存储Object的存储空间privatestaticStringbucketName="<yourBucketName>"; //目标文件privatestaticStringobjectName="upload/123.txt"; /*** 上传文件到阿里云OSS* @return*/"/upload") (publicStringupload(MultipartFilefile) throwsIOException { //验证文件是否为空if(ObjectUtils.isEmpty(file) ||file.getSize() <=0){ return"file is empty"; } InputStreaminputStream=file.getInputStream(); // 创建OSSClient实例OSSossClient=newOSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret); try { // 创建PutObjectRequest对象PutObjectRequestputObjectRequest=newPutObjectRequest(bucketName, objectName, inputStream); // 设置该属性可以返回response。如果不设置,则返回的response为空putObjectRequest.setProcess("true"); // 创建PutObject请求PutObjectResultresult=ossClient.putObject(putObjectRequest); // 如果上传成功,则返回200System.out.println(result.getResponse().getStatusCode()); } catch (Exceptione) { System.out.println("Error Message:"+e.getMessage()); } return"success"; } /*** 下载阿里云文件到本地* @return*/"/download") (publicStringdownload(StringobjName,Stringpath) throwsIOException { //下载目录StringpathName="download/123.txt"; // 创建OSSClient实例OSSossClient=newOSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret); try { // 下载Object到本地文件,并保存到指定的本地路径中ossClient.getObject(newGetObjectRequest(bucketName, objectName), newFile(pathName)); } catch (Exceptione) { System.out.println("Error Message:"+e.getMessage()); } return"success"; } }
7. Postman执行上传文件到本地目录
8. Postman执行上传到阿里云OSS
9. Postman执行从阿里云OSS下载文件到本地