后台使用的是Java SSM框架
<template>
<view>
<view class="cu-bar bg-white margin-top">
<view class="action">
图片上传
</view>
<view class="action">
{{imgList.length}}/{{imgMaxNum}}
</view>
</view>
<view class="cu-form-group">
<view class="grid col-4 grid-square flex-sub">
<view class="bg-img" v-for="(item,index) in imgList" :key="index" @tap="ViewImage" :data-url="imgList[index]">
<image :src="imgList[index]" mode="aspectFill"></image>
<view class="cu-tag bg-red" @tap.stop="DelImg" :data-index="index">
<text class='cuIcon-close'></text>
</view>
</view>
<view class="solids" @tap="ChooseImage" v-if="imgList.length<4">
<text class='cuIcon-cameraadd'></text>
</view>
</view>
</view>
<view class="cu-form-group upload-btn">
<button class="cu-btn block bg-blue margin-tb-sm lg">上传</button>
</view>
</view>
</template>
var _this = this;
export default {
data() {
return {
imgList: [],
imgMaxNum: 4
}
},
onLoad() {
},
methods: {
ChooseImage() {
_this = this;
uni.chooseImage({
count: 4, //默认9
sizeType: ['original'], //可以指定是原图还是压缩图,默认二者都有
sourceType: ['camera','album'], //从相机、相册选择
success: (res) => {
var tempFilePaths = res.tempFilePaths;
if (_this.imgList.length+tempFilePaths.length > _this.imgMaxNum) {
uni.showToast({
title: '超过上传图片的最大数量',
icon: 'none'
})
} else {
if (_this.imgList.length != 0) {
_this.imgList = _this.imgList.concat(res.tempFilePaths);
} else {
_this.imgList = res.tempFilePaths;
}
for (var i = 0; i < tempFilePaths.length; i++) {
uni.uploadFile({
url: baseUrl + "uploadImgAPP.do",
filePath: tempFilePaths[i],
name: "file", // 一定要与后台@RequestParam("file") MultipartFile变量名一致
success(res) {
console.log(res);
}
});
}
}
}
});
},
ViewImage(e) {
uni.previewImage({
urls: this.imgList,
current: e.currentTarget.dataset.url
});
},
DelImg(e) {
this.imgList.splice(e.currentTarget.dataset.index, 1)
},
}
}
@RequestMapping("uploadImgAPP")
public String uploadImgAPP(@RequestParam("file") MultipartFile file,HttpServletRequest request){
String fileName = "";
if (file != null && !file.isEmpty()) {
try {
String targetSrc = request.getServletContext().getRealPath("/")+"files";
fileName = file.getOriginalFilename();
fileName = fileName.substring(fileName.lastIndexOf("."));
fileName = UUID.randomUUID().toString() + fileName;
File targetDir = new File(targetSrc);
if (!targetDir.exists()) {
targetDir.mkdirs();
}
File targetFile = new File(targetSrc, fileName);
if (targetFile.exists()) {
targetFile.delete();
}
file.transferTo(targetFile);
} catch (Exception e) {
e.printStackTrace();
}
}
return fileName;
}