本文首發(fā)于:https://webug.io
簡(jiǎn)介
cube-ui是滴滴的一款基于Vue.js 實(shí)現(xiàn)的精致移動(dòng)端組件庫(kù)
快速使用
我們?cè)谑褂胏ube-ui之前首先需要npm進(jìn)行安裝
npm install cube-ui --save
注意:此安裝部分只針對(duì)于 vue-cli < 3 的情況
安裝完成之后需要在main.js里面import一下
import Cube from 'cube-ui'
Vue.use(Cube);
接下來(lái)在頁(yè)面中就可以調(diào)用cube-ui的組件了!!蒿偎!
示例
<cube-upload
ref="upload"
:simultaneous-uploads="1"
:max = "5"
:auto="false"
@files-added="filesAdded"
@file-removed = "filesRemoved"
/>
- simultaneous-uploads 上傳并發(fā)數(shù)
- max 最多可選擇多少?gòu)?/li>
- auto 是否自動(dòng)上傳
- files-added 選擇完圖片回調(diào)方法
- file-removed 刪除圖片回調(diào)方法
更多方法參數(shù)可見(jiàn):https://didi.github.io/cube-ui/#/zh-CN/docs/upload
具體方法實(shí)現(xiàn)
data(){
return{
imgList:[]
}
}
// 這里的files是一個(gè)文件的數(shù)組
filesAdded(files) {
let hasIgnore = false;
const limitSize = 1 * 1024;
// 最大5M
const maxSize = 5 * 1024 * 1024;
for (let i = 0; i< files.length; i++) {
const file = files[i];
// 如果選擇的圖片大小最大限制(這里為5M)則彈出提示
if(file.size > maxSize){
file.ignore = true;
hasIgnore = true;
break;
}
// 如果選擇的圖片大小大于1M則進(jìn)行圖片壓縮處理(Base64)
if(file.size > limitSize){
this.compressPic(file);
}else{
let reads= new FileReader();
reads.readAsDataURL(file);
let that = this;
reads.onload = function(e) {
var bdata = this.result;
that.imgList.push(bdata)
}
}
}
hasIgnore && this.$createToast({
type: 'warn',
time: 1000,
txt: '圖片最大支持5M'
}).show()
},
// 圖片壓縮方法
compressPic(file){
let reads= new FileReader();
reads.readAsDataURL(file)
// 注意這里this作用域的問(wèn)題
let that = this;
reads.onload = function(e) {
var bdata = this.result;
// 這里quality的范圍是(0-1)
var quality = 0.1;
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
var img = new Image();
img.src = bdata;
img.onload =function() {
var width = img.width;
canvas.width = width;
canvas.height = width * (img.height / img.width);
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
let data = canvas.toDataURL("image/jpeg",quality);
that.imgList.push(data)
}
};
}
壓縮完成之后放入imgList數(shù)組中...
捋一下大概的邏輯焦履,其實(shí)非常簡(jiǎn)單:
- 前臺(tái)選擇完成圖片會(huì)進(jìn)入filesAdded方法回調(diào)中
- 在filesAdded主要做了兩個(gè)判斷:一是選擇圖片的大小不得超過(guò)5M,二則是如果選擇的圖片大于1M則進(jìn)行壓縮氓润,否則不進(jìn)行璧帝。
- 將壓縮過(guò)的base64代碼放入imgList數(shù)組中去
這個(gè)時(shí)候我們的數(shù)據(jù)已經(jīng)拿到了叔锐,接下來(lái)要做的就是上傳到后臺(tái)去黄痪。
submit(){
const sendData = {
imgList : this.imgList
}
this.remotePost('/upload', sendData, (rsp)=> {
// 上傳成功后的業(yè)務(wù)邏輯
}
}
后臺(tái)代碼
@RequestMapping("/upload", method=RequestMethod.POST)
@ResponseBody
public RspEntity imgUpload(HttpSession session, @RequestBody Map<String, Object> reqData) throws Exception {
// 圖片列表
List<String> imgList = (List<String>)reqData.get("imgList");
// 通過(guò)for循環(huán)取出list中的base64代碼
for(String imgBase64 : imgList){
// 可通過(guò)base64轉(zhuǎn)file/byte[]等根據(jù)業(yè)務(wù)自行實(shí)現(xiàn)
}
}
另外一種方式通過(guò)后臺(tái)進(jìn)行壓縮
data(){
return{
fileList: new FormData()
}
}
filesAdded(files) {
for (let k in files) {
const file = files[k];
this.existFile = file;
this.fileList.append('files',file);
}
}
submit(){
this.remotePost('/upload', this.fileList, (rsp)=> {
// 上傳成功后的業(yè)務(wù)邏輯
}
}
這樣搞就是傳參就是file類(lèi)型的...
后臺(tái)代碼則需要進(jìn)行以下改造...
@RequestMapping("/upload", method=RequestMethod.POST)
@ResponseBody
public RspEntity imgUpload(HttpSession session, @RequestParam(value="files") MultipartFile[] files) throws Exception {
for (int i = 0; i < files.length; i++) {
MultipartFile file = files[i];
String fileType = file.getContentType();
if(StringUtils.isEmpty(fileType) || !fileType.matches("image.*")){
logger.error("上傳圖片類(lèi)型錯(cuò)誤:" + fileType);
rspEntity.setRspMsg("上傳圖片類(lèi)型錯(cuò)誤");
rspEntity.setRspCode(AppConstants.MSG_STATUS_FAIL);
return rspEntity;
}
if(file.getSize() > (long)(5 * 1024 * 1024)){
logger.error("上傳圖片大小超過(guò)限制:" + file.getSize());
rspEntity.setRspMsg("上傳圖片大小超過(guò)限制");
rspEntity.setRspCode(AppConstants.MSG_STATUS_FAIL);
return rspEntity;
}
String fileName = file.getOriginalFilename();
String temp[] = fileName.split("\\.");
if (temp.length < 2 || !temp[temp.length - 1].matches("(jpg|jpeg|png|JPG|JPEG|PNG)")) {
logger.error("上傳圖片文件名錯(cuò)誤:" + fileName);
rspEntity.setRspMsg("上傳圖片文件名錯(cuò)誤");
rspEntity.setRspCode(AppConstants.MSG_STATUS_FAIL);
return rspEntity;
}
byte[] imgCompress = CommUtil6442.compressPicForScale(file.getBytes(), 300, file.getOriginalFilename());
// 具體根據(jù)業(yè)務(wù)實(shí)現(xiàn)
}
}
這里是通過(guò)谷歌的一個(gè)圖片壓縮工具compressPicForScale紧帕,具體方法如下:
/**
* 根據(jù)指定大小壓縮圖片
*
* @param imageBytes
* 源圖片字節(jié)數(shù)組
* @param desFileSize
* 指定圖片大小,單位kb
* @param imageId
* 影像編號(hào)
* @return 壓縮質(zhì)量后的圖片字節(jié)數(shù)組
*/
public static byte[] compressPicForScale(byte[] imageBytes, long desFileSize, String imageId) {
if (imageBytes == null || imageBytes.length <= 0 || imageBytes.length < desFileSize * 1024) {
return imageBytes;
}
long srcSize = imageBytes.length;
double accuracy = getAccuracy(srcSize / 1024);
try {
while (imageBytes.length > desFileSize * 1024) {
ByteArrayInputStream inputStream = new ByteArrayInputStream(imageBytes);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(imageBytes.length);
Thumbnails.of(inputStream).scale(accuracy).outputQuality(accuracy).toOutputStream(outputStream);
imageBytes = outputStream.toByteArray();
}
logger.info("【圖片壓縮】imageId={} | 圖片原大小={}kb | 壓縮后大小={}kb", imageId, srcSize / 1024,
imageBytes.length / 1024);
} catch (Exception e) {
logger.error("【圖片壓縮】msg=圖片壓縮失敗!", e);
}
return imageBytes;
}
/**
* 自動(dòng)調(diào)節(jié)精度(經(jīng)驗(yàn)數(shù)值)
*
* @param size
* 源圖片大小
* @return 圖片壓縮質(zhì)量比
*/
private static double getAccuracy(long size) {
double accuracy;
if (size < 900) {
accuracy = 0.85;
} else if (size < 2047) {
accuracy = 0.6;
} else if (size < 3275) {
accuracy = 0.44;
} else {
accuracy = 0.4;
}
return accuracy;
}
使用之前需要在pom.xm里面引入桅打,如果不是maven項(xiàng)目則需要去網(wǎng)上搜索下載
<dependency>
<groupId>net.coobird</groupId>
<artifactId>thumbnailator</artifactId>
<version>0.4.8</version>
</dependency>
遇到的坑
我們?cè)谑褂蒙蟼鞑寮臅r(shí)候是嗜,如果不是自動(dòng)上傳,則需要將action刪除掉挺尾,不能將其設(shè)置為:action="#"鹅搪,否則會(huì)請(qǐng)求兩次。