(1)在pom.xml中配置依赖
repMaven.org.springframework spring-webmvc 5.2.15.RELEASE repMaven.org.projectlombok lombok 1.18.24 repMaven.com.fasterxml.jackson.core jackson-databind 2.13.2.2 javax.servlet javax.servlet-api 4.0.1 repMaven.commons-fileupload commons-fileupload 1.4
(2)在web.xml中注册DispatcherServlet
DispatcherServlet org.springframework.web.servlet.DispatcherServlet contextConfigLocation classpath:springmvc.xml DispatcherServlet /
(3)创建一个jsp页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
Title
<%--
method:文件的提交方式必须为post提交
enctype:默认是application/x-www-form-urlencoded(表示提交表单数据)
multipart/form-date:可以包含文件数据
type="file" 表示文件 必须有name属性
--%>
(4)在springmvc中配置文件上传解析器
(5)创建upload01接口的方法
@RequestMapping("/upload01")
public String upload01(MultipartFile myfile, HttpServletRequest request)throws Exception{
//1.得到本地服务目录的地址
String path = request.getSession().getServletContext().getRealPath("upload");
//2.判断该目录是否存在
File file = new File(path);
if(!file.exists()){
file.mkdirs();
}
//3.把myfile保存到本低服务中某个文件下
//UUID.randomUUID().toString()获取随机值 防止上传的文件名重复
//getOriginalFilename获得上传的文件名 非getName方法
String fileName = UUID.randomUUID().toString().replace("-","")
+myfile.getOriginalFilename();
File target = new File(path+"/"+fileName);
myfile.transferTo(target);//把myfile转移到目标目录下
return "";
}
3.elementui+vue+axios完成文件上传
(1)使用element+vue创建前端页面
直接使用elementui官网的模板
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
Title
(2)后台接口
@RequestMapping("upload02")
@ResponseBody
public Map upload02(MultipartFile file, HttpServletRequest request){
try {
//1.得到本低服务目录的地址
String path = request.getSession().getServletContext().getRealPath("upload");
//2.判断该目录是否存在
File file1 = new File(path);
if (!file1.exists()) {
file1.mkdirs();
}
//3.把myfile保存到本低服务中某个文件下
String fileName = UUID.randomUUID().toString().replace("-", "")
+ file.getOriginalFilename();
File target = new File(path + "/" + fileName);
file.transferTo(target);
Map map = new HashMap();
map.put("code",2000);
map.put("msg","上传成功");
//
map.put("data","http://localhost:8080/springmvc_fileupload/upload/"+fileName);
return map;
}catch (Exception e){
e.printStackTrace();
}
Map map = new HashMap();
map.put("code",5000);
map.put("msg","上传失败");
return map;
}
4.普通文件上传到OSS文件服务器
前言:可以在阿里云的oss对象存储中找到上传文件的相关代码说明
然后找到文件流上传 ---->直接复制改编代码中的值
(1)导入相关依赖
dependency>
com.aliyun.oss
aliyun-sdk-oss
3.10.2
(2)测试代码
package com.wx.controller;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import java.io.FileInputStream;
import java.io.InputStream;
public class Demo {
public static void main(String[] args){
// Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。
//自己的密钥 复制粘贴即可
String accessKeyId = "";
String accessKeySecret = "";
// 填写自己创建的Bucket名称,
String bucketName = "michihana";
// 填写Object完整路径,完整路径中不能包含Bucket名称,可以随便起个文件或者图片的名称。
String objectName = "aa.jpg";
// 填写本地文件的完整路径(绝对路径),例如D:\localpath\examplefile.txt。
String filePath= "C:\Users\11319\Pictures\cc.jpg";
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
try {
InputStream inputStream = new FileInputStream(filePath);
// 创建PutObject请求。
ossClient.putObject(bucketName, objectName, inputStream);
} catch (OSSException oe) {
System.out.println("Caught an OSSException, which means your request made it to OSS, "
+ "but was rejected with an error response for some reason.");
System.out.println("Error Message:" + oe.getErrorMessage());
System.out.println("Error Code:" + oe.getErrorCode());
System.out.println("Request ID:" + oe.getRequestId());
System.out.println("Host ID:" + oe.getHostId());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
}
}
然后运行 就可以在自己的bucket列表中看到
接下来代码为使用springmvc在前端页面上传图片到阿里云,然后会在另一个页面回显上传的图片
(1)前端代码
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
Title
(2)将上诉上传的代码写在一个工具类中,后续调用即可(放直书写重复代码)
package com.wx.utils;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import org.springframework.web.multipart.MultipartFile;
import java.io.InputStream;
import java.util.Calendar;
import java.util.UUID;
public class OSSUtils {
public static String upload(MultipartFile myFile){
String endpoint = "oss-cn-hangzhou.aliyuncs.com";
//直接复制自己的密钥
String accessKeyId = "";
String accessKeySecret = "";
String bucketName = "";
//获得当前时间年月日,可以将文件夹的名字变为当天时间
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH)+1;
int day = calendar.get(Calendar.DATE);
//通过UUID工具类获取随机值 防止文件名重复 覆盖之前的文件
String objectName = year+"/"+month+"/"+day+"/"
+ UUID.randomUUID().toString().replace("-","")
+myFile.getOriginalFilename();
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
try {
InputStream inputStream = myFile.getInputStream();
ossClient.putObject(bucketName, objectName, inputStream);
} catch (OSSException oe) {
System.out.println("Caught an OSSException, which means your request made it to OSS, "
+ "but was rejected with an error response for some reason.");
System.out.println("Error Message:" + oe.getErrorMessage());
System.out.println("Error Code:" + oe.getErrorCode());
System.out.println("Request ID:" + oe.getRequestId());
System.out.println("Host ID:" + oe.getHostId());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
String url = "https://"+bucketName+"."+endpoint+"/"+objectName;
//将上传后的路径名得到,这样就能回显上传后的图片
return url;
}
}
(3)在控制层写在请求路径(/upload)的代码
@Controller
public class UploadFileController {
@RequestMapping("upload")
public String upload(MultipartFile myFile, HttpServletRequest request) throws Exception{
//静态方法 直接通过类名调用即可
String url = OSSUtils.upload(myFile);
//将得到的url保存到session中这样就可以在另一个页面回显图片
request.setAttribute("imgUrl",url);
//跳转页面的路径
return "success.jsp";
}
}
(4)回显图片的页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
Title
<%--el表达式 直接用即可--%>
运行效果图
(1)前端页面,可在官网找相关代码 直接复制即可 引入相关elementui的css和js样式
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
Title
(2)控制层代码
//自定义公共类 为了给前端返回json格式数据
@RequestMapping("upload01")
@ResponseBody
public Result upload01(MultipartFile file){
try {
//直接调用上述的工具类
//注意 elementui的官网的文件名 默认为file 除非修改name属性
//所以传递参数的时候只能将形参定义为file
String url = OSSUtils.upload(file);
Result result = new Result(2000,"上传成功",url);
//将结果集变为json格式 返回给前端 让前端得到url 从而回显数据
return result;
} catch (Exception e) {
e.printStackTrace();
}
return new Result(5000,"上传失败",null);
}
运行效果图
通过elementui+axious+vue+springmvc实现用户信息的添加(带头像)
注意:要保证实体类中的属性名和前端传递的数据的v-model中的属性名一致
(1)前端页面代码
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
Title
提交
效果图
(2)实体层代码
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private String name;
private String pwd;
private String address;
private String avatar;
}
(3)controller代码
@RequestMapping("adduser")
@ResponseBody
public Result addUser(@RequestBody User user){
if(user!=null){
//未连接数据库 在这里输出得到的user对象的值 后续连接数据库即可保存到数据库中
System.out.println(user);
Result result = new Result(2000,"添加成功",null);
return result;
}else{
return new Result(5000,"添加失败",null);
}
}
6.springmvc中的注解
1.@RestController ---等价于@Controller+@ResponseBody ---该注解所有的方法都是返回json数据
2.@RequestMapping:作用:把请求路径映射到响应的方法上。
3. @RequestPara(value="u"):设置接收的请求参数名,一般用于查询
4.@RequestMapping(value = "/addUser",method = RequestMethod.POST)
method:有get和post两种 表示该接口接受的请求方式.不设置可以接受任意请求方式。
5.@GetMapping("addUser"):表示只接受get提交方式的请求
6.@RequestBody:把请求的json数据转换为java对象。从前端到后端
7.@ResponseBody:把java转换为json数据 从后端转前端



