前端(element-plus):
<div>
<el-upload
v-model:file-list="fileList" list-type="picture-card" :on-preview="handlePictureCardPreview"
:auto-upload=false //关闭自动上传
:limit=6>//最多上传6张。更多API请到Element Plus上查看
<Icon icon="ep:plus" />
</el-upload>
<el-dialog v-model="dialogVisible">
<img w-full :src="dialogImageUrl" alt="Preview Image" />
</el-dialog>
</div>
前端(vue):
//TS接口所在文件夹位置
import { SqsVehicleVerificationApi} from '@/api/control/***'
//导入element-plus组件
import { FormInstance, FormRules, UploadProps, UploadUserFile } from 'element-plus';
const fileList = ref<UploadUserFile[]>([])
const dialogImageUrl = ref('')
const dialogVisible = ref(false)
// const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
// console.log(uploadFile, uploadFiles)
// }
const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
dialogImageUrl.value = uploadFile.url!
dialogVisible.value = true
}
//这是我的表单提交的方式,配合后台的
const submitForm = () => {
//关键:定义提交表单数据类型
const formData = new FormData();
//关键:循环该数组,把该图片的file类型放到表单里
fileList.value.forEach((ele) => {
if (ele.status === 'ready') {
formData.append('files', ele.raw as any)
}
})
//弹窗表单里输入的数据,根据自己的来
const editparams = reactive({
id: '1',//id
name: 'aa'
})
//JSON.stringify(editparams)是将对象转换为字符串,也叫序列化
formData.append('Model',JSON.stringify(editparams))//表单数据添加
//该方法是访问后台的方法你也可直接在此使用ajax或者axios访问后台提交formData 表单
//注意:因是FormData类型,post方法记得将头的数据类型改为multipart/form-data
EditModel(formData);
}
/** 访问后台的方法 */
const EditModel = async (prams: FormData) => {
try {
const data = await SqsVehicleVerificationApi.EditApplication(prams)
} finally {
}
}
以上两部分是直接在element-plus官网拷贝的,根据自己需求改下即可。
ts访问后端部分:
//将SqsVehicleVerificationApi 暴露出来给vue使用
export const SqsVehicleVerificationApi = {
//我这里是大佬封装好的axios。自行百度axiospost请求即可,或者使用ajax也行,此处不是关键
//数据提交类型记得设置为multipart/form-data
EditApplication : async (formData: FormData) => {
return await request.post({ url: `/control/sqs-loadingandshipping-manage/EditVerificationApplication`,data:formData,headersType:'multipart/form-data'})
},
}
后台(JAVA MVC)
//这是控制器方法
//@ModelAttribute("files")取出前台定义的files变量
//@ModelAttribute("Model") 取出前台定义的Model变量
//HttpServletRequest request用来获取服务端路径信息,里面也包含了前台传过来的数据
PostMapping("/EditVerificationApplication")
@Operation(summary = "編輯申请")
public CommonResult<Boolean>EditApplicationDatas(@ModelAttribute("files") List<MultipartFile> files,
@ModelAttribute("Model") String model,HttpServletRequest request) {
Integer ServerPort = request.getServerPort(); // 服务端端口
String Address =request.getScheme() + "://"+request.getServerName()+":"+ServerPort+"/api/file/";
//JSONObject jsonObject=JSONObject.parseObject(model);
//反序列化映射字段及数据,SqsCreateVehicleApplicationVO 改为自己的类,字段不比数量相等,不过得包含前台数据字段名称与类型
SqsCreateVehicleApplicationVO data= JSONObject.parseObject(model, SqsCreateVehicleApplicationVO.class);
String Imagepath="";
if(files.stream().count()>0){
for (MultipartFile file : files) {
try {
//UploadAndDownloadUtil是保存文件的方法
String path=Address+UploadAndDownloadUtil.SaveSingleFile(file);
Imagepath+="#"+path+"#";
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
//给图片路径赋值
data.setVerificationImage(Imagepath);
//这是具体存入数据库的逻辑,此处不贴了
sqsManageService.EditApplicationDatas(data);
return success(true);
}
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 {
private static String PathBase="E:\\Images";
public static String SaveSingleFile(MultipartFile file) throws Exception{
String uploadAbsPath = PathBase;
//判断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 fineName;
}
/**
*上传单个文件
* @param file
* @param request
* @return 上传文件的路径
* @throws Exception
*/
public static 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(PathBase);
// 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 PathBase + File.separator + fineName;
}
public ServletOutputStream downloadSingleFile (String filePathName, HttpServletResponse response) throws Exception {
//通过输入流读取文件的内容
FileInputStream fileInputStream = new FileInputStream(PathBase + 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;
}
}
重点:映射本地磁盘路径(这样返回的路径才可被前端直接调用显示图片):
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class ImagePathConfigurer implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
//配置资源映射:设置虚拟路径,访问绝对路径下资源:访问 http://localhost:8080/api/file/xxx.jpg访问E:/Images/下的资源
//若访问设有拦截,请在拦截器处设置httpSecurity.antMatchers("/api/file/**").permitAll()//使访问本地图片资源不会被拦截
//本项目的拦截位置在ProductionWebSecurityConfigurerAdapter类处
registry.addResourceHandler("/api/file/**") //虚拟路径
.addResourceLocations("file:///" + "E:/Images/"); //绝对路径以/结尾
}
}
END.......................................