1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > java vue elementui 上传照片墙

java vue elementui 上传照片墙

时间:2024-01-23 19:26:50

相关推荐

java vue elementui 上传照片墙

批量上传图片

后端使用的是java,前端使用vue+elementui。

前端部分

首先要设置组件中auto-upload属性为false,取消自动上传,multiple属性为true,支持多文件上传,http-request自定义的上传方法。

使用new FormData()创建FormData对象发送至后台

<template><el-uploadaction="/api/file/uploadImgs" //上传地址ref="upload"list-type="picture-card" //设置文件列表样式:on-preview="handlePictureCardPreview" //点击文件列表时:on-success="handSuccess" //上传成功:on-error="handError" //上传失败:limit=3 //最大上传个数:on-exceed="handExceed" //文件超出限制:file-list="fileList" //文件列表:multiple="true" //是否支持多文件上传:http-request="uploadFile" //自定义上传方法:auto-upload="false"> //是否自动上传<i class="el-icon-plus"></i></el-upload><el-dialog :visible.sync="dialogVisible"><img width="100%" :src="dialogImageUrl" alt=""></el-dialog><el-button type="primary" @click="submit">上传</el-button></template><script>export default {data() {fileList: [], //存放要上传的图片列表fileData:'',},methods: {// 点击图片handlePictureCardPreview(file) {this.dialogImageUrl = file.url;this.dialogVisible = true;},// 图片上传超过限制handExceed(file, fileList){this.$message.error('最多只能上传三张')},// 图片上传成功handSuccess(response, file, fileList){this.$message.success('图片上传成功!')},// 图片上传失败handError(err, file, fileList){this.$message.error('图片上传失败!')},// 自定义上传uploadFile:function(file){/***file是文件名后台需要用@RequestParam(value="file")接收*/this.fileData.append('file', file.file);},// 提交到后台submit(){this.fileData = new FormData();this.$refs.upload.submit(); //多文件会多次提交/***如果提交的时候需要携带其他参数,继续在fileData后面追加数据就行了,如这里传入一个id*后台也需要用@RequestParam(value="id")接收*/this.fileData.append('id',12)this.$axios.post('/api/file/uploadImgs', this.fileData).then(res => {console.log(res)}).catch(error => {console.log(error)})}}</script>

后端部分

控制层代码

@PostMapping(value = "/upload")public void upload(@RequestParam("files") MultipartFile[] files) {// 调用业务层,这里简写service.upload(files);}

业务层

/*** 批量上传* @param files 文件数组* @return list 文件信息*/List<Map<String, Object>> upload(MultipartFile[] files);

实现层

@Override@Transactional(rollbackFor = Exception.class)public List<Map<String, Object>> upload(MultipartFile[] files) {List<Map<String, Object>> list = new ArrayList<>();for (MultipartFile multipartFile : files) {list.add(create(multipartFile));}return list;}/*** 上传文件*/public Map<String,Object> create(MultipartFile multipartFile) {Map<String,Object> map = new HashMap<>(16);// 检查文件大小FileUtil.checkSize(10L, multipartFile.getSize());// 获取文件后缀名String suffix = FileUtil.getExtensionName(multipartFile.getOriginalFilename());// 获取文件类型String type = FileUtil.getFileType(suffix);// 获取服务器地址(用于拼接地址,前端可直接访问资源,根据实际需要来做)String httpUrl = properties.getPath().getHttpUrl();// 获取文件存储根路径(根据实际业务改动)String filePath = properties.getPath().getPath();File file = FileUtil.upload(multipartFile, filePath + type + File.separator);if(ObjectUtil.isNull(file)){throw new BadRequestException("上传失败");}try {String name = FileUtil.getFileNameNoEx(multipartFile.getOriginalFilename());// 封装一个文件具体信息,用于存入数据库,根据自己的业务需求改动即可LocalStorage localStorage = new LocalStorage(file.getName(),name,suffix,file.getPath(),httpUrl+"/file/"+type+"/"+file.getName(),type,FileUtil.getSize(multipartFile.getSize()));// TODO 保存实体,数据库操作,省略map.put("picture_url","/file/"+type+"/"+file.getName());map.put("picture_full_url",httpUrl+"/file/"+type+"/"+file.getName());return map;}catch (Exception e){FileUtil.del(file);throw e;}}

工具类 FileUtil 对hutool的FileUtil进行了扩展

public class FileUtil extends cn.hutool.core.io.FileUtil {/*** 定义GB的计算常量*/private static final int GB = 1024 * 1024 * 1024;/*** 定义MB的计算常量*/private static final int MB = 1024 * 1024;/*** 定义KB的计算常量*/private static final int KB = 1024;/*** 格式化小数*/private static final DecimalFormat DF = new DecimalFormat("0.00");/*** 检查文件大小* @param maxSize 文件最大M* @param size 上传文件的大小*/public static void checkSize(long maxSize, long size) {int len = 1024 * 1024;if (size > (maxSize * len)) {throw new BadRequestException("文件超出规定大小");}}/*** 获取不带扩展名的文件名*/public static String getFileNameNoEx(String filename) {if ((filename != null) && (filename.length() > 0)) {int dot = filename.lastIndexOf('.');if ((dot > -1) && (dot < (filename.length()))) {return filename.substring(0, dot);}}return filename;}/*** 获取文件扩展名,不带 .*/public static String getExtensionName(String filename) {if ((filename != null) && (filename.length() > 0)) {int dot = filename.lastIndexOf('.');if ((dot > -1) && (dot < (filename.length() - 1))) {return filename.substring(dot + 1);}}return filename;}/*** 文件大小转换*/public static String getSize(long size) {String resultSize;if (size / GB >= 1) {//如果当前Byte的值大于等于1GBresultSize = DF.format(size / (float) GB) + "GB ";} else if (size / MB >= 1) {//如果当前Byte的值大于等于1MBresultSize = DF.format(size / (float) MB) + "MB ";} else if (size / KB >= 1) {//如果当前Byte的值大于等于1KBresultSize = DF.format(size / (float) KB) + "KB ";} else {resultSize = size + "B ";}return resultSize;}/*** 获取文件类型*/public static String getFileType(String type) {String documents = "txt doc pdf ppt pps xlsx xls docx";String music = "mp3 wav wma mpa ram ra aac aif m4a";String video = "avi mpg mpe mpeg asf wmv mov qt rm mp4 flv m4v webm ogv ogg";String image = "bmp dib pcp dif wmf gif jpg tif eps psd cdr iff tga pcd mpt png jpeg";if (image.contains(type)) {// 图片return "image";} else if (documents.contains(type)) {// 文档return "documents";} else if (music.contains(type)) {// 音乐return "music";} else if (video.contains(type)) {// 视频return "video";} else {// 其他return "其他";}}/*** 将文件名解析成文件的上传路径*/public static File upload(MultipartFile file, String filePath) {Date date = new Date();SimpleDateFormat format = new SimpleDateFormat("yyyyMMddhhmmssS");// 获取后缀名String name = getFileNameNoEx(file.getOriginalFilename());// 获取文件名String suffix = getExtensionName(file.getOriginalFilename());String nowStr = "-" + format.format(date);try {// 拼接文件名String fileName = name + nowStr + "." + suffix;// 拼接文件目录String path = filePath + fileName;// 可解析正确各种路径File dest = new File(path).getCanonicalFile();// 检测是否存在目录if (!dest.getParentFile().exists()) {if (!dest.getParentFile().mkdirs()) {System.out.println("was not successful.");}}// 文件写入file.transferTo(dest);return dest;} catch (Exception e) {e.printStackTrace();}return null;}}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。