写在前面(准备工作):
(1)依赖引入
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.19</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.24</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.13.2.2</version>
</dependency>
<!-- 文件上传依赖 commons-fileupload-->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
<!-- oss依赖-->
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.10.2</version>
</dependency>
DispatcherServlet配置
DispatcherServlet是Spring MVC中最核心的对象;DispatcherServlet用于拦截Http请求;并根据请求的URL,找到与之对应的Controller控制器中的方法,来完成对该Http请求的处理
<!-- dispatcherServlet-->
<servlet>
<servlet-name>DispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>DispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
(3)在springmvc配置文件中配置文件上传解析器
<?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.lcy.controller"/>
<mvc:annotation-driven/>
<!-- 静态处理-->
<mvc:default-servlet-handler/>
<!-- <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">-->
<!-- <property name="maxUploadSize" value="10485760"/>-->
<!-- </bean>-->
<!-- 配置文件上传配置 id必须为multipartResolver-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="10485760"/>
</bean>
</beans>
(4)阿里云OSS
之后依据密钥对Bucket进行上传文件(可以理解为id和密码,输入后可以确认身份进行上传)
准备工作完成
1. 进行文件上传
(1)先去阿里云官方给的OSS帮助文档中查看安装(这里前面已经引入过以来了)
(2) 查看文件流上传(这是官网给的上传代码,根据上面提示进行修改)
package com.lcy.controller;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.UUID;
/**
* @Author Lcy
* @Date 2022/6/9
*/
@Controller
public class UploadController {
@RequestMapping("upload03")
public String upload03(MultipartFile myfile, HttpServletRequest request) throws IOException {
// Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。
String endpoint = "oss-cn-hangzhou.aliyuncs.com";
// 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。
String accessKeyId = "你的密钥id";
String accessKeySecret = "你的密钥密码";
// 填写Bucket名称,例如examplebucket。
String bucketName = "luckylcy";
// 填写Object完整路径,完整路径中不能包含Bucket名称,例如exampledir/exampleobject.txt。
LocalDateTime ldt = LocalDateTime.now();
String objectName = ldt.getYear() + "/" + ldt.getMonthValue() + "/" + ldt.getDayOfMonth() +
"/" + UUID.randomUUID().toString().replace("-","") + myfile.getOriginalFilename();
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
try {
InputStream inputStream = myfile.getInputStream();
// 创建PutObject请求。
ossClient.putObject(bucketName, objectName, inputStream);
} catch (Exception e){
e.printStackTrace();
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
// http://luckylcy.oss-cn-hangzhou.aliyuncs.com/2022/6/10/08e69a25ebb74fdcbf165f63730286b8yl.png
String url = "http://" + bucketName + "." + endpoint + "/" + objectName;
request.setAttribute("imgUrl",url);
return "success.jsp";
}
}
(3)创建页面
<%--
Created by IntelliJ IDEA.
User: lcy28
Date: 2022/6/9
Time: 18:50
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<form method="post" action="/upload03" enctype="multipart/form-data">
<input type="file" name="myfile"/><br>
<input type="submit" value="提交"/>
</form>
</body>
</html>
(4)运行Tomcat,进行文件上传
提交成功后,就可以通过网址进行访问了。
3. ElementUI + Vue + axios 进行文件上传。
(1)页面设计
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<!--引入element得css样式-->
<link type="text/css" rel="stylesheet" href="css/index.css"/>
<!--引入vue得js文件 这个必须在element之前引入-->
<script type="text/javascript" src="js/vue.js"></script>
<script type="text/javascript" src="js/qs.min.js"></script>
<script type="text/javascript" src="js/axios.min.js"></script>
<!--element得js文件-->
<script type="text/javascript" src="js/index.js"></script>
<style>
.avatar-uploader .el-upload {
border: 1px dashed #d9d9d9;
border-radius: 6px;
cursor: pointer;
position: relative;
overflow: hidden;
}
.avatar-uploader .el-upload:hover {
border-color: #409EFF;
}
.avatar-uploader-icon {
font-size: 28px;
color: #8c939d;
width: 178px;
height: 178px;
line-height: 178px;
text-align: center;
}
.avatar {
width: 178px;
height: 178px;
display: block;
}
</style>
</head>
<body>
<div id="app">
<el-form label-width="80px" :model="userForm">
<el-form-item label="头像">
<el-upload
class="avatar-uploader"
action="/uploadAvatar"
:show-file-list="false"
:on-success="handleAvatarSuccess"
:before-upload="beforeAvatarUpload">
<img v-if="imageUrl" :src="imageUrl" class="avatar">
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
</el-form-item>
<el-form-item label="姓名">
<el-input v-model="userForm.name"></el-input>
</el-form-item>
<el-form-item label="住址">
<el-input v-model="userForm.address"></el-input>
</el-form-item>
<el-form-item label="注册日期">
<el-input v-model="userForm.date"></el-input>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="submitForm">提交</el-button>
</el-form-item>
</el-form>
</div>
</body>
<script>
var app = new Vue({
el:"#app",
data: {
imageUrl: '',
userForm:{},
},
methods: {
handleAvatarSuccess(res, file) {
if(res.code === 2000){
this.imageUrl = res.data;
this.userForm.imgUrl = res.data;
this.$message.success(res.message)
}else {
this.$message.error(res.message)
}
},
beforeAvatarUpload(file) {
const isJPG = file.type === 'image/jpeg';
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isJPG) {
this.$message.error('上传头像图片只能是 JPG 格式!');
}
if (!isLt2M) {
this.$message.error('上传头像图片大小不能超过 2MB!');
}
return isJPG && isLt2M;
},
submitForm(){
axios.post("addUser",this.userForm).then(function (result){
if(result.code === 2000){
this.$message.success(result.message)
}
})
}
}
})
</script>
</html>
(2) 把上传文件的代码封装到一个Util工具类中,并设计一个CommonResult类:处理器接收信息处理后返回的数据(返回的是一个字符串,表示上传后文件的访问路径)
package com.lcy.util;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.web.multipart.MultipartFile;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.UUID;
/**
* @Author Lcy
* @Date 2022/6/10
*/
public class OSSUtil {
public static String upload(MultipartFile file){
// Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。
String endpoint = "oss-cn-hangzhou.aliyuncs.com";
// 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。
String accessKeyId = "你的密钥id";
String accessKeySecret = "你的密钥密码";
// 填写Bucket名称,例如examplebucket。
String bucketName = "luckylcy";
// 填写Object完整路径,完整路径中不能包含Bucket名称,例如exampledir/exampleobject.txt。
LocalDateTime ldt = LocalDateTime.now();
String objectName = ldt.getYear() + "/" + ldt.getMonthValue() + "/" + ldt.getDayOfMonth() +
"/" + UUID.randomUUID().toString().replace("-","") + file.getOriginalFilename();
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
try {
InputStream inputStream = file.getInputStream();
// 创建PutObject请求。
ossClient.putObject(bucketName, objectName, inputStream);
} catch (Exception e){
e.printStackTrace();
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
// http://luckylcy.oss-cn-hangzhou.aliyuncs.com/2022/6/10/08e69a25ebb74fdcbf165f63730286b8yl.png
String url = "http://" + bucketName + "." + endpoint + "/" + objectName;
return url;
}
}
package com.lcy.util;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* @Author Lcy
* @Date 2022/6/10
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class CommonResult {
private Integer code;
private String message;
private Object data;
}
(3)设计Controller
package com.lcy.controller;
import com.lcy.entity.User;
import com.lcy.util.CommonResult;
import com.lcy.util.OSSUtil;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
/**
* @Author Lcy
* @Date 2022/6/10
*/
@RestController
public class UserController {
@RequestMapping("uploadAvatar")
@ResponseBody
public CommonResult uploadAvatar(MultipartFile file){
try {
String filePath = OSSUtil.upload(file);
return new CommonResult(2000, "头像上传成功", filePath);
}catch (Exception e){
e.printStackTrace();
}
return new CommonResult(2000, "头像上传失败", null);
}
}
此时,文件已经可以上传了并进行回显了。
(4)增加User实体类,用来封装前台传来的数据
package com.lcy.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.format.annotation.DateTimeFormat;
import java.util.Date;
/**
* @Author Lcy
* @Date 2022/6/10
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
private String imgUrl;
private String name;
private String address;
@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date date;
}
(5)在设计User添加的Controller类
@RequestMapping("addUser")
public CommonResult addUser(@RequestBody User user){
//接收到前台传来的数据后,应该通过service对数据库进行增加,再次不做处理,仅仅打印出信息
System.out.println(user);
return new CommonResult(2000, "添加用户成功", null);
}
(6)测试