当前位置:网站首页>Use of file upload (2) -- upload to Alibaba cloud OSS file server
Use of file upload (2) -- upload to Alibaba cloud OSS file server
2022-07-29 05:53:00 【Don't want bald Xiao Yang】
1. Upload to the local server for review
1. Upload ordinary files to the local server . Form submission data .
2.elementui Complete asynchronous upload to the local server .
Disadvantages of uploading files to local servers ?
1. When the server restarts , The local service file is missing .
2. Build a server cluster .A The server 1000, B The server .........
The first time the customer uploads, they visit A The server .
The customer accesses the file for the second time , What I visited was B The server .
How to solve the shortcomings of local server uploading :
(1) Build a file server by yourself . Won't restart . maintain .
(2) Use a third-party file server .
2. Ordinary files are uploaded to OSS File server


(1) Introducing Alibaba cloud dependency

<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.10.2</version>
</dependency>(2) Code writing

@RequestMapping("/upload03")
public String upload03(MultipartFile myfile,HttpServletRequest request){
// Endpoint East China 1( Hangzhou ) For example , Other Region Please fill in according to the actual situation .
String endpoint = "oss-cn-hangzhou.aliyuncs.com";
//LTAI78XQAZq2s5Rv
//qdyZxR0x4LoUpTVbuyvCGdcrhEyw7H
// Alicloud account AccessKey Have all the API Access rights of , The risk is high . It is highly recommended that you create and use it RAM The user carries out API Visit or daily operations , Please log in RAM Console creation RAM user .
String accessKeyId = "********";
String accessKeySecret = "**************";
// Fill in Bucket name , for example examplebucket.
String bucketName = "qy151";
// You upload to oss The name after Will help you create folders according to the date .
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();
// establish OSSClient example .
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
try {
InputStream inputStream =myfile.getInputStream();
// establish PutObject request .
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 Asynchronous upload OSS The server
(1) front end
<%--
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>
<!-- introduce element have to css style -->
<link type="text/css" rel="stylesheet" href="css/index.css"/>
<!-- introduce vue have to js file This has to be element Introduced before -->
<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 have to js file -->
<script type="text/javascript" src="js/index.js"></script>
</head>
<body>
<div id="app">
<%--action: File upload path --%>
<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:{
// Method triggered after successful upload
handleAvatarSuccess(res, file) {
this.imageUrl=res.data;
},
// Method triggered before uploading
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(' Uploading a picture of your head can only be JPG Format !');
}
if (!isLt2M) {
this.$message.error(' The size of the uploaded image cannot exceed 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) Back end tools
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 East China 1( Hangzhou ) For example , Other Region Please fill in according to the actual situation .
String endpoint = "oss-cn-hangzhou.aliyuncs.com";
//LTAI78XQAZq2s5Rv
//qdyZxR0x4LoUpTVbuyvCGdcrhEyw7H
// Alicloud account AccessKey Have all the API Access rights of , The risk is high . It is highly recommended that you create and use it RAM The user carries out API Visit or daily operations , Please log in RAM Console creation RAM user .
String accessKeyId = "LTAI78XQAZq2s5Rv";
String accessKeySecret = "qdyZxR0x4LoUpTVbuyvCGdcrhEyw7H";
// Fill in Bucket name , for example examplebucket.
String bucketName = "qy151";
// You upload to oss The name after Will help you create folders according to the date .
String objectName =fileName(myfile);
// establish OSSClient example .
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
try {
InputStream inputStream =myfile.getInputStream();
// establish PutObject request .
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;
}
// Get uploaded to oss The name after
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 Interface
@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", " Upload successful ");
map.put("data", url);
return map;
} catch (Exception e) {
e.printStackTrace();
}
HashMap map = new HashMap();
map.put("code", 5000);
map.put("msg", " Upload failed ");
return map;
}4. Save user information -- Head portrait
(1) Front end layout
<%--
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>
<!-- introduce element have to css style -->
<link type="text/css" rel="stylesheet" href="css/index.css"/>
<!-- introduce vue have to js file This has to be element Introduced before -->
<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 have to js file -->
<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=" Head portrait :">
<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=" account number :">
<el-input v-model="userForm.name"></el-input>
</el-form-item>
<el-form-item label=" password :">
<el-input v-model="userForm.pwd"></el-input>
</el-form-item>
<el-form-item label=" Address :">
<el-input v-model="userForm.address"></el-input>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="onSubmit"> Inquire about </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;
// Add the attribute of avatar address to the form object
this.userForm.avatarUrl=this.imageUrl;
},
// Submit
onSubmit(){
axios.post("/addUser",this.userForm).then(function(result){
});
},
// Method triggered before uploading
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(' Uploading a picture of your head can only be JPG Format !');
}
if (!isLt2M) {
this.$message.error(' The size of the uploaded image cannot exceed 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) Back end code
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, " Upload successful ", avatar);
} catch (Exception e) {
e.printStackTrace();
}
return new CommonResult(5000, " Failure ", null);
}
//@RequestBody: Put the request in the body json Data to java object
@RequestMapping("/addUser")
@ResponseBody
public CommonResult addUser(@RequestBody User user){
System.out.println(user);
//TODO call dao Finish saving to the database -- Omit
return new CommonResult(2000," success ",null);
}
}
5. Scattered content
@RestController---- Class equivalent to @[email protected]
All methods under this annotation return json data
@RequestMapping: effect : Map the request path to the response method .@RequestParam(value = "u"): Set the parameter name of the request you accept . Query parameters
@RequestMapping(value = "/addUser",method = RequestMethod.POST)
method: Indicates the request mode accepted by the interface . It is not set to accept any request .
@GetMapping("addUser"): Means to accept only get Request submitted by@RequestBody: Request json Data to java object . From front end to back end
@ResponseBody: hold java Convert to json data From the back to the front

边栏推荐
- win10+opencv3.2+vs2015配置
- “山东大学移动互联网开发技术教学网站建设”项目实训日志六
- 获取水仙花数
- 农村品牌建设给年轻人的一些机会
- 与张小姐的春夏秋冬(2)
- 7 月 28 日 ENS/USD 价值预测:ENS 吸引巨额利润
- Gluster cluster management analysis
- Most PHP programmers don't understand how to deploy safe code
- Simple optimization of interesting apps for deep learning (suitable for novices)
- centos7 静默安装oracle
猜你喜欢

浅谈分布式全闪存储自动化测试平台设计

识变!应变!求变!

D3.JS 纵向关系图(加箭头,连接线文字描述)

Crypto giants all in metauniverse, and platofarm may break through

完全去中心化的编程模式,不需要服务器,也不需要ip,就像一张漫无目的的网络、四处延伸

How can Plato obtain premium income through elephant swap in a bear market?

Starfish OS:以现实为纽带,打造元宇宙新范式

"Shandong University mobile Internet development technology teaching website construction" project training log V

焕然一新,swagger UI 主题更改

Xsan is highly available - xdfs and San are integrated with new vitality
随机推荐
“山东大学移动互联网开发技术教学网站建设”项目实训日志六
C# 连接 SharepointOnline WebService
H5 semantic label
Shanzhai coin Shib has a US $548.6 million stake in eth whale's portfolio - traders should be on guard
Under the bear market of encrypted assets, platofarm's strategy can still obtain stable income
超简单集成HMS ML Kit 人脸检测实现可爱贴纸
深度学习的趣味app简单优化(适合新手)
Flink connector Oracle CDC 实时同步数据到MySQL(Oracle19c)
Read and understand move2earn project - move
“山东大学移动互联网开发技术教学网站建设”项目实训日志五
Okaleido tiger logged into binance NFT on July 27, and has achieved good results in the first round
与张小姐的春夏秋冬(4)
"Shandong University mobile Internet development technology teaching website construction" project training log I
Simple optimization of interesting apps for deep learning (suitable for novices)
“山东大学移动互联网开发技术教学网站建设”项目实训日志一
熊市下PLATO如何通过Elephant Swap,获得溢价收益?
Laravel服务容器(继承与事件)
完全去中心化的编程模式,不需要服务器,也不需要ip,就像一张漫无目的的网络、四处延伸
Reporting Services- Web Service
xSAN高可用—XDFS与SAN融合焕发新生命力