我的環境是nuxt+el-upload+Springboot;
<template>
<div>
<el-upload
class="upload-demo"
action="http://xball.henengsoft.com:8092/hn/uploads"
:limit="1"
accept="image/*"
:on-exceed = "onExceed"
:on-change="handleChange"
:on-success="uploadSuccess"
:before-upload="beforeUnload"
:beforeUpload="beforeAVatarUpload"
:auto-upload="false"
ref="upload"
:file-list="fileList">
<el-button size="small" type="primary">點擊上傳</el-button>
<div slot="tip" class="el-upload__tip">只能上傳jpg/png文件,且不超過500kb</div>
</el-upload>
<button @click="sc">上傳</button>
<img :src="path" style="width: 400px"/>
<!-- <el-upload drag multiple
name="multipartfiles" //後臺接收文件流的參數名
ref="upload"
:limit="limit" //限制文件數量
:action="imageAction" //上傳圖片的訪問的服務器路徑
:data="uploadData" //需要攜帶的其他參數
:on-preview="handlePreview" //點擊時觸發的事件
:on-remove="handleRemove" //點擊移除文件時觸發的事件
:file-list="fileList" //已上傳的文件list
:beforeUpload="beforeAVatarUpload" //上傳之前觸發的事件,我在這裏做了上傳文件的類型控制
:on-exceed = "onExceed" //和limit一起用 當文件數量超出限制時觸發
:onError="uploadError" //上傳失敗時觸發
:onSuccess="uploadSuccess" //上傳成功時觸發
:auto-upload="true"> //是否自動上傳
<i class="el-icon-upload"></i>
<div class="el-upload__text">將圖片拖到此處,或<em>點擊上傳</em></div>
<div class="el-upload__tip" slot="tip">只能上傳'jpg/png/jpeg/gif'</div>
</el-upload>-->
</div>
</template>
<script>
export default {
name:'cs',
data() {
return {
fileList: [],
path:'',
};
},
methods: {
handleChange(file, fileList) {
this.fileList = fileList.slice(-3);
console.log(fileList)
},
handleAvatarSuccess(){
this.$message({type: 'success', message: '上傳成功', showClose: true});
},
uploadSuccess(e){
this.path="http://xball.henengsoft.com:8092/hn/file/download?filename="+e.path;
console.log(e.path)
},
beforeUnload(){
//自動上傳觸發
if(this.fileList.length>1){
this.fileList.splice(1,1);
this.$message({type: 'info', message: '請刪除資源後重新上傳', showClose: true});
return false;
}
return true;
},
sc(){
//手動提交
//和表單一起提交,先提交圖片,後提交表單
this.$refs.upload.submit()
},
onExceed(){
//手動上傳限制
this.$message({type: 'info', message: '請刪除資源後重新選擇', showClose: true});
},
beforeAVatarUpload(file) {
let _this = this
//resolve:同意
//reject:拒絕
return new Promise((resolve, reject) => {
debugger
let isLt2M = file.size / 1024 / 1024 > 0.1 // 判定圖片大小是否小於100k
if(!isLt2M) {
resolve()
}
let image = new Image(), resultBlob = '';
image.src = URL.createObjectURL(file);
image.onload = () => {
// 調用方法獲取blob格式,方法寫在下邊
resultBlob = _this.compressUpload(image);
resolve(resultBlob)
}
image.onerror = () => {
reject()
}
})
},
/* 圖片壓縮方法-canvas壓縮 */
compressUpload(image) {
let canvas = document.createElement('canvas')
let ctx = canvas.getContext('2d')
let initSize = image.src.length
let { width } = image, { height } = image
canvas. width = width
canvas.height = height
ctx.fillRect(0, 0, canvas.width, canvas.height)
ctx.drawImage(image, 0, 0, width, height)
// 進行最小壓縮0.1
let compressData = canvas.toDataURL('image/jpeg', 0.1)
// 壓縮後調用方法進行base64轉Blob,方法寫在下邊
let blobImg = this.dataURItoBlob(compressData)
return blobImg
},
/* base64轉Blob對象 */
dataURItoBlob(data) {
let byteString;
if(data.split(',')[0].indexOf('base64') >= 0) {
byteString = atob(data.split(',')[1])
}else {
byteString = unescape(data.split(',')[1])
}
let mimeString = data
.split(',')[0]
.split(':')[1]
.split(';')[0];
let ia = new Uint8Array(byteString.length)
for( let i = 0; i < byteString.length; i += 1) {
ia[i] = byteString.charCodeAt(i)
}
return new Blob([ia], {type: mimeString})
}
}
}
</script>
<style scoped>
</style>
我這裏分兩步提交,先上傳圖片在上傳圖片成功的回調函數uploadSuccess()提交表單;
@RequestMapping(value = "/uploads", method = RequestMethod.POST)
public R file(@RequestParam("file") MultipartFile file) {
String filePath="";
if (!file.isEmpty()) {
try {
int begin = file.getOriginalFilename().indexOf(".");
int last = file.getOriginalFilename().length();
//獲得文件後綴名
String a = file.getOriginalFilename().substring(begin, last);
String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase();
uuid += a;
String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
String paths= path + date + "\\";
// 判斷文件是否爲空
File file1 = new File(paths);
if (!file1.exists()) {
file1.mkdirs();//創建
}
// 文件保存路徑
filePath = paths
+ uuid;
// 轉存文件
file.transferTo(new File(filePath));
} catch (Exception e) {
e.printStackTrace();
}
}else
return R.error("文件不存在");
try {
filePath = java.net.URLEncoder.encode(filePath, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return R.ok().put("path", filePath);
}
後臺就是存儲圖片並返回圖片路徑,第二次提交表單時一起提交。