当前位置:网站首页>File文件上传的使用(2)--上传到阿里云Oss文件服务器
File文件上传的使用(2)--上传到阿里云Oss文件服务器
2022-07-29 05:20:00 【不想秃头的小杨】
1.上传到本地服务器得到回顾
1.普通文件上传到本地服务器。表单提交数据。
2.elementui完成异步上传到本地服务器。
文件上传到本地服务器的缺点?
1. 当服务器重启,本地服务的文件没了。
2. 搭建服务器集群。A服务器1000, B服务器.........
客户第一次上传时访问的是A服务器。
客户第二次访问文件,访问的是B服务器。
如何解决本地服务器上传的缺点:
(1)自己搭建一个文件服务器。不会重启。维护。
(2) 使用第三方的文件服务器.
2. 普通的文件上传到OSS文件服务器
(1)引入阿里云的依赖
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.10.2</version>
</dependency>
(2)代码的书写
@RequestMapping("/upload03")
public String upload03(MultipartFile myfile,HttpServletRequest request){
// Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。
String endpoint = "oss-cn-hangzhou.aliyuncs.com";
//LTAI78XQAZq2s5Rv
//qdyZxR0x4LoUpTVbuyvCGdcrhEyw7H
// 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。
String accessKeyId = "********";
String accessKeySecret = "**************";
// 填写Bucket名称,例如examplebucket。
String bucketName = "qy151";
//你上传到oss后的名字 会根据日期帮你创建文件夹。
Calendar calendar=Calendar.getInstance();
String objectName =calendar.get(Calendar.YEAR)+"/"+(calendar.get(Calendar.MONTH)+1)+"/"+
calendar.get(Calendar.DATE)+"/"+UUID.randomUUID().toString().replace("-","")+
myfile.getOriginalFilename();
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
try {
InputStream inputStream =myfile.getInputStream();
// 创建PutObject请求。
ossClient.putObject(bucketName, objectName, inputStream);
} catch (Exception oe) {
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
//https://qy151.oss-cn-hangzhou.aliyuncs.com/2022/6/10/20d3d7e6b5bb455cb548675501f7270fgdnj.jpg
String url="https://"+bucketName+"."+endpoint+"/"+objectName;
request.setAttribute("imgUrl",url);
return "success.jsp";
}
3. elementui 异步上传OSS服务器
(1)前端
<%--
Created by IntelliJ IDEA.
User: YSH
Date: 2022/6/10
Time: 8:53
To change this template use File | Settings | File Templates.
--%>
<%@ 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>
</head>
<body>
<div id="app">
<%--action:文件上传的路径--%>
<el-upload
class="avatar-uploader"
action="/upload04"
: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>
</div>
</body>
<script>
var app=new Vue({
el:"#app",
data:{
imageUrl:"",
},
methods:{
//上传成功后触发的方法
handleAvatarSuccess(res, file) {
this.imageUrl=res.data;
},
//上传前触发的方法
beforeAvatarUpload(file) {
const isJPG = file.type === 'image/jpeg';
const isPNG = file.type === 'image/png';
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isJPG) {
this.$message.error('上传头像图片只能是 JPG 格式!');
}
if (!isLt2M) {
this.$message.error('上传头像图片大小不能超过 2MB!');
}
return isJPG && isLt2M;
}
}
})
</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>
</html>
(2)后端工具
package com.ysh.utils;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.web.multipart.MultipartFile;
import java.io.InputStream;
import java.util.Calendar;
import java.util.UUID;
/**
* @program: qy151-springmvc-upload
* @description:
* @author: YSH
* @create: 2022-06-11 9:00
**/
public class OSSUtils {
public static String upload(MultipartFile myfile){
// Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。
String endpoint = "oss-cn-hangzhou.aliyuncs.com";
//LTAI78XQAZq2s5Rv
//qdyZxR0x4LoUpTVbuyvCGdcrhEyw7H
// 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。
String accessKeyId = "LTAI78XQAZq2s5Rv";
String accessKeySecret = "qdyZxR0x4LoUpTVbuyvCGdcrhEyw7H";
// 填写Bucket名称,例如examplebucket。
String bucketName = "qy151";
//你上传到oss后的名字 会根据日期帮你创建文件夹。
String objectName =fileName(myfile);
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
try {
InputStream inputStream =myfile.getInputStream();
// 创建PutObject请求。
ossClient.putObject(bucketName, objectName, inputStream);
} catch (Exception oe) {
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
//https://qy151.oss-cn-hangzhou.aliyuncs.com/2022/6/10/20d3d7e6b5bb455cb548675501f7270fgdnj.jpg
String url="https://"+bucketName+"."+endpoint+"/"+objectName;
return url;
}
//获取上传到oss后的名字
private static String fileName(MultipartFile myfile){
Calendar calendar=Calendar.getInstance();
String name=calendar.get(Calendar.YEAR)+"/"+(calendar.get(Calendar.MONTH)+1)+"/"+
calendar.get(Calendar.DATE)+"/"+ UUID.randomUUID().toString().replace("-","")+
myfile.getOriginalFilename();
return name;
}
}
(3)controller接口
@RequestMapping("/upload04")
@ResponseBody
public Map upload04(MultipartFile file) {
try {
String url = OSSUtils.upload(file);
Map map = new HashMap();
map.put("code", 2000);
map.put("msg", "上传成功");
map.put("data", url);
return map;
} catch (Exception e) {
e.printStackTrace();
}
HashMap map = new HashMap();
map.put("code", 5000);
map.put("msg", "上传失败");
return map;
}
4.保存用户信息--头像
(1)前端的布局
<%--
Created by IntelliJ IDEA.
User: YSH
Date: 2022/6/11
Time: 8:45
To change this template use File | Settings | File Templates.
--%>
<%@ 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>
</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.pwd"></el-input>
</el-form-item>
<el-form-item label="地址:">
<el-input v-model="userForm.address"></el-input>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="onSubmit">查询</el-button>
</el-form-item>
</el-form>
</div>
</body>
<script>
var app=new Vue({
el:"#app",
data:{
userForm:{},
imageUrl:""
},
methods:{
handleAvatarSuccess(result,file){
this.imageUrl=result.data;
//为表单对象添加头像地址的属性
this.userForm.avatarUrl=this.imageUrl;
},
//提交
onSubmit(){
axios.post("/addUser",this.userForm).then(function(result){
});
},
//上传前触发的方法
beforeAvatarUpload(file) {
const isJPG = file.type === 'image/jpeg';
const isPNG = file.type === 'image/png';
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isJPG) {
this.$message.error('上传头像图片只能是 JPG 格式!');
}
if (!isLt2M) {
this.$message.error('上传头像图片大小不能超过 2MB!');
}
return isJPG && isLt2M;
}
}
})
</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>
</html>
(2)后端代码
package com.ysh.controller;
import com.ysh.entity.User;
import com.ysh.utils.CommonResult;
import com.ysh.utils.OSSUtils;
import org.springframework.stereotype.Controller;
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.multipart.MultipartFile;
/**
* @program: qy151-springmvc-upload
* @description:
* @author: YSH
* @create: 2022-06-11 9:23
**/
@Controller
public class UserController {
@RequestMapping("uploadAvatar")
@ResponseBody
public CommonResult uploadAvatar(MultipartFile file) {
try {
String avatar = OSSUtils.upload(file);
return new CommonResult(2000, "上传成功", avatar);
} catch (Exception e) {
e.printStackTrace();
}
return new CommonResult(5000, "失败", null);
}
//@RequestBody:把请求体中json数据转换为java对象
@RequestMapping("/addUser")
@ResponseBody
public CommonResult addUser(@RequestBody User user){
System.out.println(user);
//TODO 调用dao完成保存到数据库--省略
return new CommonResult(2000,"成功",null);
}
}
5.零零散散的内容
@RestController----类上等价于 @[email protected]
该注解下所有的方法都是返回json数据
@RequestMapping: 作用: 把请求路径映射到响应的方法上。@RequestParam(value = "u"):设置你接受的请求参数名。查询参数
@RequestMapping(value = "/addUser",method = RequestMethod.POST)
method:表示该接口接受的请求方式.不设置可以接受任意请求方式。
@GetMapping("addUser"):表示只接受get提交方式的请求@RequestBody:把请求的json数据转换为java对象。从前端到后端
@ResponseBody:把java转换为json数据 从后端转前端
边栏推荐
- How can Plato obtain premium income through elephant swap in a bear market?
- Detailed steps of JDBC connection to database
- 以‘智’提‘质|金融影像平台解决方案
- 微信内置浏览器禁止缓存的问题
- 数组的基础使用--遍历循环数组求出数组最大值,最小值以及最大值下标,最小值下标
- Laravel service container (inheritance and events)
- PHP如何生成二维码?
- “山东大学移动互联网开发技术教学网站建设”项目实训日志六
- datax安装
- NIFI 改UTC时间为CST时间
猜你喜欢
随机推荐
Breaking through the hardware bottleneck (I): the development of Intel Architecture and bottleneck mining
ThinkPHP6 输出二维码图片格式 解决与 Debug 的冲突
Differences between href and SRC
Fantom (FTM) prices will soar by 20% in the next few days
What is nmap and how to use it
Extreme deflation and perpetual motion machine model will promote the outbreak of platofarm
DAY13:文件上传漏洞
Detailed steps of JDBC connection to database
DAO赛道异军突起,M-DAO的优势在哪里?
识变!应变!求变!
Go|gin quickly use swagger
以‘智’提‘质|金融影像平台解决方案
北京宝德&TaoCloud共建信创之路
What is sqlmap and how to use it
裸金属云FASS高性能弹性块存储解决方案
The completely decentralized programming mode does not need servers or IP, just like a aimless network extending everywhere
xtrabackup 的使用
From starfish OS' continued deflationary consumption of SFO, the value of SFO in the long run
“山东大学移动互联网开发技术教学网站建设”项目实训日志一
Plato farm is expected to further expand its ecosystem through elephant swap