vue代码
<template>
<el-upload
name="image"
class="avatar-uploader"
action="http://localhost:8080/cellphone/uploadImage"
:show-file-list="false"
:on-success="handleAvatarSuccess"
:before-upload="beforeAvatarUpload"
>
<img v-if="image" :src="image" class="avatar" />
<el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
</el-upload>
<template/>
<script setup>
import {ref} from "vue";
import { ElMessage } from 'element-plus';
const image = ref(null);
const handleAvatarSuccess = (
response,
uploadFile
) => {
console.log('response',response)
image.value = "http://localhost:8080/"+response
console.log('uploadFile',uploadFile)
// console.log('image',image.value)
}
//上传文件时做的处理
const beforeAvatarUpload = (rawFile) => {
console.log("rawFile",rawFile);
console.log(rawFile.type);
console.log(rawFile.size/1024/1024);
if ( rawFile.type.split("/")[0] != 'image' ){
ElMessage.error('不是图片!')
return false
}else if (rawFile.size / 1024 / 1024 > 2) {
ElMessage.error('头像图片大小不能超过2MB!')
return false
}
return true
}
</script>
<style scoped>
.demo-image__error .image-slot {
font-size: 30px;
}
.demo-image__error .image-slot .el-icon {
font-size: 30px;
}
.demo-image__error .el-image {
width: 100%;
height: 200px;
}
.avatar-uploader .avatar {
width: 178px;
height: 178px;
display: block;
}
</style>
<style >
.avatar-uploader .el-upload {
border: 1px dashed var(--el-border-color);
border-radius: 6px;
cursor: pointer;
position: relative;
overflow: hidden;
transition: var(--el-transition-duration-fast);
}
.avatar-uploader .el-upload:hover {
border-color: var(--el-color-primary);
}
.el-icon.avatar-uploader-icon {
font-size: 28px;
color: #8c939d;
width: 178px;
height: 178px;
text-align: center;
}
</style>
java代码
package com.itzhigui.utils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.util.UUID;
/**
* 文件上传和下载工具类
*/
@Component
public class UploadAndDownloadUtil {
/**
*上传单个文件
* @param file
* @param request
* @return 上传文件的路径
* @throws Exception
*/
public String uploadSingleFile(MultipartFile file,HttpServletRequest request) throws Exception{
//获取项目部署的绝对路径
ServletContext application = request.getSession().getServletContext();
//F:\我的资料\web\后端\java\wook\spring-mvc-project\target\spring-mvc-project
//获取upload目录的绝对路径
String uploadAbsPath = application.getRealPath(ConstantUtil.UPLOAD_FILE_DIR);
// String uploadAbsPath = "F:\\我的资料\\web\\后端\\java\\wook\\最新项目\\cellPhone-java\\target"+ConstantUtil.UPLOAD_FILE_DIR;
//判断upload目录是否存在,如果存在就不需要创建
File uploadDir = new File(uploadAbsPath);
if (!uploadDir.exists()){
//upload目录不存在
uploadDir.mkdirs(); //创建目录,递归创建 例如:a/b/c
}
//==========================upload目录是存在=========================
//文件上传
//getOriginalFilename():获取原本文件的名称
// FilenameUtils.getExtension:获取原始文件的后缀,
String extension = FilenameUtils.getExtension(file.getOriginalFilename());
//生成上传的文件名称 (随机生成: UUID.randomUUID().toString().replaceAll("-","")+".jpg";)
String fineName = UUID.randomUUID().toString().replaceAll("-","")+"."+extension;
//定义上传文件的绝对路径
//separator:表示分割符 系统默认给分割符(/),(比如每个电脑的操作系统不一样分隔符就不一样可以让电脑自己决定)
String uploadFileAbsPath = uploadAbsPath+File.separator+fineName;
//创建空文件
File dest = new File(uploadFileAbsPath);
//执行上传文件
file.transferTo(dest);
return ConstantUtil.UPLOAD_FILE_DIR + File.separator + fineName;
}
public ServletOutputStream downloadSingleFile (String filePathName, HttpServletResponse response) throws Exception {
//通过输入流读取文件的内容
FileInputStream fileInputStream = new FileInputStream(ConstantUtil.UPLOAD_FILE_DIR + filePathName);
//通过输出流将文件返回给浏览器展示
ServletOutputStream outputStream = response.getOutputStream();
//设置文件类型
response.setContentType("image/jpeg");
int len = 0;
byte[] bytes = new byte[1024];
while ((len = fileInputStream.read(bytes)) != -1){
outputStream.write(bytes, 0, len);
outputStream.flush();//清空缓存
}
//关闭资源
outputStream.close();
fileInputStream.close();
return outputStream;
}
}
@PostMapping("/uploadImage")
public String uploadImage(
MultipartFile image,
HttpServletRequest request
) {
String s = null;
try {
s = uploadAndDownloadUtil.uploadSingleFile(image, request);
} catch (Exception e) {
e.printStackTrace();
}
return s;
}