1.Base64文件上传
myaxios.js
axios.interceptors.request.use(function (config) {
config.baseURL = "http://localhost:8088/"
// config.headers.Authorization = "Bearer " + localStorage.getItem("token")
return config;
}, function (error) {
return Promise.reject(error);
});
/**
* 每次请求完成之后 先走这个方法
*/
axios.interceptors.response.use(function (response) {
let {status, message, data} = response.data;
if (status === 20000) {
return data;
} else {
if (status === 40009) {
$("#activeBtn").css("display","block");
}
toastr.error(message)
}
return Promise.reject(false);
}, function (error) {
return Promise.reject(error);
});
1.1.前端JS
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>文件上传</title>
</head>
<body>
<div id="app">
<img :src="ImgUpload" alt="" ref="image" height="100px" width="100px"/>
<input type="file" @change="Upload">
</div>
<script src="./myjs/vue.js"></script>
<script src="./myjs/axios.min.js"></script>
<script src="./myjs/myaxios.js"></script>
<script>
let vue = new Vue({
el: '#app',
data: {
ImgUpload: ''
},
methods: {
Upload(e) {
//通过base64预览
let file = e.target.files[0]
let fileReader = new FileReader();
//获取文件扩展名
let substr = file.name.substr(file.name.lastIndexOf(".")+1);
//读取文件,是一个异步操作
fileReader.readAsDataURL(file)
//回调函数,表示已经读后
fileReader.onloadend = function (e) {
let result = e.target.result;
//此方案可以动态设置src属性
this.ImgUpload = result;
//此方案可以动态设置src属性
//this.$refs.image.src=base64;
//防止乱码,传送json
let obj = {
//base64
base64: result,
//扩展名
ext:substr
}
axios.post(`common/uploadBase64`, obj).then(response => {
})
}.bind(this)
}
}
})
</script>
</body>
</html>
1.2.后端
/**
* base64上传文件
*/
@PostMapping("uploadBase64")
public AxiosResult<String> uploadBase64(@RequestBody Map<String,String> map){
String base64 = map.get("base64");
String ext = map.get("ext");
/**
* 云存储
*/
//指定的是endPoint 去对应的bucket的概述中查找(查找外网访问的)
String endpoint = "https://oss-cn-beijing.aliyuncs.com";
String accessKeyId = "阿里云密钥";
String accessKeySecret = "阿里云密钥";
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
/*
参数一: 表示上传到哪个bucket 取值就是云存储上面的bucket的名称
参数二: 表示文件名 (必须加后缀)
参数三: 文件流
*/
base64 = base64.split(",")[1];
byte[] bytes = Base64Utils.decodeFromString(base64);
ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
String fileName = System.nanoTime() + "." + ext;
ossClient.putObject("ershibaqi", fileName, inputStream);
ossClient.shutdown();
return AxiosResult.success("https://ershibaqi.oss-cn-beijing.aliyuncs.com/" + fileName);
}
2.Part文件上传
2.1.前端JS
let vue = new Vue({
el: "#app",
created() {
this.findAll();
},
data: {
tableData: [],
currentPage: 1,
pageSize: 3,
total: 1000,
maxPage: 6,
search: '',
formData: {},
imgUrl: '../dist/img/avatar.png'
},
methods: {
findAll() {
axios.get(`goods?currentPage=${this.currentPage}&pageSize=${this.pageSize}&search=${this.search}`).then(response => {
this.total = response.total;
this.tableData = response.data;
});
},
//头像上传
chooseFile(e) {
let file = e.target.files[0];
let formData = new FormData();
formData.append("goodsImg", file);
axios.post(`common/upload`, formData, {headers: {'content-Type': 'multipart/form-data'}}).then(response => {
this.imgUrl = response;
this.formData.goodsImg = response;
})
}
}
})
2.2.后端
controller
/**
* 上传文件
*/
@PostMapping("upload")
public AxiosResult<String> upload(@RequestPart Part goodsImg) throws IOException, ServletException {
String upload = UploadUtils.upload(goodsImg);
return AxiosResult.success(upload);
}
utils
/**
* 上传文件到阿里云工具类
*/
public class UploadUtils {
public static String upload(Part part) {
//指定的是endPoint 去对应的bucket的概述中查找(查找外网访问的)
String endpoint = "https://oss-cn-beijing.aliyuncs.com";
String accessKeyId = "阿里云密钥";
String accessKeySecret = "阿里云密钥";
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
//通过文件Part获取流程
InputStream inputStream = null;
try {
inputStream = part.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
/*
参数一: 表示上传到哪个bucket 取值就是云存储上面的bucket的名称
参数二: 表示文件名 (必须加后缀)
参数三: 文件流
*/
String fileName = System.nanoTime() + "." + StringUtils.getFilenameExtension(part.getSubmittedFileName());
ossClient.putObject("ershibaqi", fileName, inputStream);
ossClient.shutdown();
System.out.println(part.getSubmittedFileName());
return "https://ershibaqi.oss-cn-beijing.aliyuncs.com/" + fileName;
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/192920.html