当前位置:网站首页>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

边栏推荐
- 农村品牌建设给年轻人的一些机会
- Thinkphp6管道模式Pipeline使用
- 机器学习让文字识别更简单:Kotlin+MVVM+华为ML Kit
- "Shandong University mobile Internet development technology teaching website construction" project training log I
- Markdown语法
- Gluster集群管理小分析
- 山寨币SHIB 在 ETH 鲸鱼的投资组合中拥有 5.486 亿美元的股份——交易者应提防……
- Breaking through the hardware bottleneck (I): the development of Intel Architecture and bottleneck mining
- 手撕ORM 框架(泛型+注解+反射)
- 『全闪实测』数据库加速解决方案
猜你喜欢

How to make interesting apps for deep learning with zero code (suitable for novices)

深度学习的趣味app简单优化(适合新手)

“山东大学移动互联网开发技术教学网站建设”项目实训日志七

ThinkPHP6 输出二维码图片格式 解决与 Debug 的冲突

Huawei 2020 school recruitment written test programming questions read this article is enough (Part 2)

Xsan is highly available - xdfs and San are integrated with new vitality

Thinkphp6管道模式Pipeline使用

中海油集团,桌面云&网盘存储系统应用案例

The completely decentralized programming mode does not need servers or IP, just like a aimless network extending everywhere

MOVE PROTOCOL全球健康宣言,将健康运动进行到底
随机推荐
Madonna "hellent" bought $1.3 million NFT boring ape, which is now considered too expensive
The bear market is slow, and bit.store provides stable stacking products to help you get through the bull and bear market
『全闪实测』数据库加速解决方案
Starfish OS: create a new paradigm of the meta universe with reality as the link
Machine learning makes character recognition easier: kotlin+mvvm+ Huawei ml Kit
Read and understand move2earn project - move
深度学习的趣味app简单优化(适合新手)
Fantom (FTM) 在 FOMC会议之前飙升 45%
Training log III of "Shandong University mobile Internet development technology teaching website construction" project
如何零代码制作深度学习的趣味app(适合新手)
Windows下cmd窗口连接mysql并操作表
农村品牌建设给年轻人的一些机会
Extreme deflation and perpetual motion machine model will promote the outbreak of platofarm
Laravel Swagger添加访问密码
Plato Farm有望通过Elephant Swap,进一步向外拓展生态
新手入门:手把手从PHP环境到ThinkPHP6框架下载
Detailed steps of JDBC connection to database
闪贷Dapp的调研及实现
“山东大学移动互联网开发技术教学网站建设”项目实训日志五
xtrabackup 的使用