<!-- uview中的头像组件 @click头像点击事件 -->
<u-avatar :src="" size="144" @click="albumClick">
data(){
return{
uploadUrl: "后台地址/upload",
}
}
methods:{
// 相册选择图片
albumClick() {
var _this = this
let src = {};
_this.show = false;
uni.chooseImage({
count: 1, //默认9
sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图,默认二者都有
sourceType: ['album'], //从相册选择
success: function(res) {
const tempFilePaths = res.tempFilePaths
uni.uploadFile({ // 调用文件上传
url: _this.uploadUrl, // 上传的地址
filePath: tempFilePaths[0], // 上传的图片地址
fileType: 'image', // 确定上传文件类型
name: 'file',
success: (res)=> {
// 头像信息
_this.headPortrait = JSON.parse(res.data).data.urlPath
// 获取后台返回的网址
this.upload() // 文件地址存数据库
},
fail: (err)=> {
uni.$u.toast("上传失败")
}
})
},
});
},
}
后台配置:
#标识图片上传的路径 application.yml
file:
#本地存储的根目录
localDir: D:/JT-SOFT/image
#网络访问虚拟路径 nginx配置
urlPath: http://image.jt.com
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
@Data
@Accessors(chain = true)
@NoArgsConstructor
@AllArgsConstructor
public class ImageVO {
private String virtualPath; //文件动态路径
private String urlPath; // 文件网络路径
private String fileName; // 文件名称
}
private String localDir = "D:/images/upload"; // 本地图片保存地址
private String urlPath = "http://image.jt.com";
@Override
public ImageVO upload(MultipartFile file) {
// 防止大小写问题,将所有字母转化为小写
String fileName = file.getOriginalFilename().toLowerCase();
//利用正则判断是否为图片
if (!fileName.matches("^.+\\.(jpg|png|gif|jpeg)$")) {
//如果校验不通过,则终止程序
return null;
}
System.out.println("图片类型正确的!!!!!!");
//第二步 防止恶意程序 判断图片是否有宽度和高度
try {
BufferedImage bufferedImage =
ImageIO.read(file.getInputStream());
int width = bufferedImage.getWidth();
int height = bufferedImage.getHeight();
if (width == 0 || height == 0) {
return null;
}
System.out.println("用户上传的是图片");
//第三步: 目录如何划分 yyyy/MM/dd
String dateDir = new SimpleDateFormat("/yyyy/MM/dd/")
.format(new Date());
String dirPath = localDir + dateDir;
File dirFile = new File(dirPath);
if (!dirFile.exists()) {
//如果目录不存在时, 创建目录
dirFile.mkdirs();
}
//第四步: 使用uuid实现文件名称 uuid.jpg
//4.1 生成UUID
String uuid = UUID.randomUUID()
.toString().replace("-", "");
//截取文件类型
int index = fileName.lastIndexOf(".");
String fileType = fileName.substring(index);
//生成新文件名称
String newFile = uuid + fileType;
//第五步:实现文件上传 全路径 再上传
String path = dirPath + newFile;
file.transferTo(new File(path));
System.out.println("文件上传成功!!!!");
//第六步: 返回ImageVO数据
//6.1 虚拟路径只写动态变化的数据 /2021/11/11/uuid.jpg
String virtualPath = dateDir + newFile;
//6.2 真实图片名称
String fileNameVO = newFile;
//6.3 网络地址 http://image.jt.com/xx/uuid.jpg
String url = urlPath + virtualPath;
return new ImageVO(virtualPath, url, fileNameVO);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}