背景
最近在搞一个项目中的单个图像识别功能,功能下有两个场景,分别是有/无用户信息时的图片识别,要求将图片保存至服务器,用作历史记录。
环境
前端使用Vue2,ElementUi框架,后端使用SpringBoot,图像识别使用Pytorch(下面就不展开描述了)。上传组件使用ElementUi的el-upload组件。
代码
页面
<el-upload
class="el_upload_show"
drag
action="http://地址+端口号/*/species_recognition"
:auto-upload="true"
:on-change="imgSaveToUrl"
:accept="'image/*'"
:data = {userName:userName} //这里时附带的参数信息,在data声明下
:on-success="upload_success"
:show-file-list="false"
:before-upload="before_upload"
>
<i class="el-icon-upload"></i>
<div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div>
<div class="el-upload__text">只能上传图片文件</div>
</el-upload>
JS部分
/文件上传前:结果显示加载中
before_upload(){
this.res_loading = true
},
//上传成功返回路径
upload_success(res,file){
if(res.message == 'success'){
dao.species_recognition(res.data).then( reslut => {
const sortedObj = Object.entries(reslut.data.top).sort((a, b) => b[1] - a[1]).reduce((acc, [key, value]) => ({ ...acc, [key]: value }), {})
const arr = Object.keys(sortedObj).map(key => ({
recognition_name: this.LSM_label.find( a => a.en==key).cn,
probability: sortedObj[key]
}))
let sum = 0
arr.forEach(a => sum+=a.probability)
arr.forEach(a => a.probability = a.probability/sum)
this.recognition_res = arr
this.res_loading = false
})
}
},
imgSaveToUrl(event) {
// 获取上传图片的本地URL,用于上传前的本地预览展示
var URL = null;
if (window.createObjectURL != undefined) {
// basic
URL = window.createObjectURL(event.raw);
} else if (window.URL != undefined) {
// mozilla(firefox)
URL = window.URL.createObjectURL(event.raw);
} else if (window.webkitURL != undefined) {
// webkit or chrome
URL = window.webkitURL.createObjectURL(event.raw);
}
this.localUrl = URL;
},
后端
Controller层
@ResponseBody
@RequestMapping("species_recognition")
public ResultVo species_recognition(String userName,MultipartFile file,HttpServletRequest request){
String path = "";
if ("".equals(userName)){ //用户未登录
path = fileService.species_recognition_Without_user(file,tmp_file);
}else{
path = fileService.species_recognition(userName,file,server_file_path);
}
//
return ResultVo.success(path);
}
其中的
tmp_file和server_file_path是从yml文件中获得的全局变量。
ServiceImpl层
@Override
public String species_recognition(String userName, MultipartFile file, String server_file_path) {
String folder = server_file_path+"/"+userName+"/"+"species_recognition";
File folderFile = new File(folder);
String oldName = file.getOriginalFilename();
String newName = oldName.split("\\.")[0] + "-" + UUID.randomUUID().toString()+oldName.substring(oldName.lastIndexOf("."));
if (!folderFile.exists()) {
folderFile.mkdirs();
}
try{
file.transferTo(new File(folderFile,newName));
return folder+"/"+newName;
}catch (IOException e){
log.info(file.getOriginalFilename()+"存储出错:"+ DateUtil.DateToString(new Date()));
return null;
}
}
项目还在完善,功能还不太成熟,可以将日志按照需求进行数据库的持久化。
最后,初步完成的效果如下所示。