锋哥原创的uniapp微信小程序投票系统实战:
XML
<view class="option_item" v-for="(item,index) in options" :key="item.id">
<view class="option_input">
<text class="removeOption" @click="removeOption(item.id)"></text><input type="text" v-model="item.name" placeholder="输入选项名称" placeholder-style="color:#bababa;font-size:14px">
</view>
<view class="option_upload">
<uni-file-picker
@select="selectVoteItemFileFunc($event,index)"
:auto-upload="false"
limit="1"
:del-icon="false"
disable-preview
file-mediatype="image"
:imageStyles="voteItemImageStyles">
<view class="upload">
<text class="smallUploadImg"></text>
</view>
</uni-file-picker>
</view>
</view>
css
.option_item{
margin-top: 10px;
border-radius: 5px;
background-color: white;
padding: 10px;
.option_input{
display: flex;
}
.option_upload{
margin-top: 20rpx;
.upload{
margin: 10rpx;
background-color: #f4f5f7;
width:90rpx;
height: 90rpx;
display: flex;
align-items: center;
justify-content: center;
}
}
}
css
voteItemImageStyles:{
width:"150rpx",
height:"120rpx",
border:false
},
javascript
selectVoteItemFileFunc:function(e,index){
console.log("index="+index)
console.log(e.tempFilePaths[0])
uni.uploadFile({
header:{token:uni.getStorageSync("token")},
url:getBaseUrl()+"/vote/uploadVoteItemImage",
filePath:e.tempFilePaths[0],
name:"voteItemImage",
success: (res) => {
let result=JSON.parse(res.data);
if(result.code==0){
this.options[index].image=result.voteItemImageFileName;
}
}
})
},
加个image属性:
提交加上验证:
javascript
// 验证投票选项,如果有名称的,必须要上传图片
for(var i=0;i<this.options.length;i++){
var option=this.options[i];
if(!isEmpty(option.name)){
if(isEmpty(option.image)){
console.log("请上传第"+(i+1)+"个投票选项图片")
uni.showToast({
icon:"error",
title:"请上传第"+(i+1)+"个投票选项图片"
})
return;
}
}
}
后端:
javascript
voteItemImagesFilePath: D://uniapp/voteItemImgs/
javascript
@Value("${voteItemImagesFilePath}")
private String voteItemImagesFilePath;
java
/**
* 上传投票选项图片
* @param voteItemImage
* @return
* @throws Exception
*/
@RequestMapping("/uploadVoteItemImage")
public Map<String,Object> uploadVoteItemImage(MultipartFile voteItemImage)throws Exception{
System.out.println("filename:"+voteItemImage.getName());
Map<String,Object> resultMap=new HashMap<>();
if(!voteItemImage.isEmpty()){
// 获取文件名
String originalFilename = voteItemImage.getOriginalFilename();
String suffixName=originalFilename.substring(originalFilename.lastIndexOf("."));
String newFileName= DateUtil.getCurrentDateStr()+suffixName;
FileUtils.copyInputStreamToFile(voteItemImage.getInputStream(),new File(voteItemImagesFilePath+newFileName));
resultMap.put("code",0);
resultMap.put("msg","上传成功");
resultMap.put("voteItemImageFileName",newFileName);
}
return resultMap;
}