<el-upload
ref="upload"
:before-upload="uploadSectionFile"
:action="fileupaction"
list-type="picture-card"
:on-remove="handleRemove"
:on-success="success"
:file-list="filelist"
:on-change="changeSectionFile"
>
<i class="el-icon-plus" />
</el-upload>
<el-dialog :visible.sync="dialogVisible">
<img width="100%" :src="dialogImageUrl" alt="">
</el-dialog>
handleRemove(file, fileList) {
console.log(this.imgs)
if (this.$route.query.id != null) {
const url = file.url.replace('http://localhost:8080/', '')
this.imgs = this.imgs.replace(url + ',', '')
} else {
this.imgs = this.imgs.replace(file.response.data + ',', '')
}
console.log(this.imgs)
},
success(response, file) {
if (response.code === 200) {
this.dialogImageUrl = response.data
this.imgs = this.imgs + this.dialogImageUrl + ','
}
console.info(this.imgs)
},
uploadSectionFile(file) {
var testmsg = file.name.substring(file.name.lastIndexOf('.') + 1).toLocaleLowerCase()
const extension =
testmsg === 'jpg' ||
testmsg === 'png' ||
testmsg === 'jpeg'
const isLt2M = file.size / 1024 / 1024 < 1
if (!extension) {
this.$message.error('上传头像图片只能是 JPG/PNG 格式!')
return false
} else if (!isLt2M) {
this.$message.error('上传头像图片大小不能超过 2MB!')
return false
} else {
return extension && isLt2M
}
},
changeSectionFile(file) {
var testmsg = file.name.substring(file.name.lastIndexOf('.') + 1).toLocaleLowerCase()
const extension =
testmsg === 'jpg' ||
testmsg === 'png' ||
testmsg === 'jpeg'
const isLt2M = file.size / 1024 / 1024 < 2
return extension && isLt2M
},
//获取图片列表
getImgsList({ id: this.$route.query.id}).then(function(res) {
console.info(res)
const imgarray = []
res.data.forEach(function(data, index) {
imgarray.push({ name: index, url: 'http://localhost:8080/' + data.photo })
_this.imgs += data.photo + ','
})
_this.filelist = imgarray
})
package com.lostperson.controller;
import com.lostperson.vo.AjaxResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
@RestController
@RequestMapping("/file")
public class FileUploadController {
private String imgString;
@Value("${image.uploadurl}")
private String uppath;
@PostMapping("/upload")
public AjaxResult uploadFile(@RequestParam("file") MultipartFile file) {
// 判断文件是否为空
if (file.isEmpty()) {
return AjaxResult.error("上传文件不能为空");
}
// 获取传过来的文件名字
String OriginalFilename = file.getOriginalFilename();
//判断文件类型
String type = OriginalFilename.substring(OriginalFilename.lastIndexOf(".") + 1).toLowerCase();
if (!type.equals("jpg") && !type.equals("png") && !type.equals("jpeg")) {
return AjaxResult.error("不是图片");
}
// //获取jar包所在目录
// ApplicationHome h = new ApplicationHome(getClass());
// File jarF = h.getSource();
// //在jar包所在目录下生成一个upload文件夹用来存储上传的图片
// String filePath = jarF.getParentFile().toString() + "/classes/static/upload/";
String filePath = uppath + "/upload/";
// 保存头像文件的文件夹
File dir = new File(filePath);
if (!dir.exists()) {
dir.mkdirs();
}
// 为了防止重名覆盖,获取系统时间戳+原始文件的后缀名
String fileName = System.currentTimeMillis() + "." + OriginalFilename.substring(OriginalFilename.lastIndexOf(".") + 1);
File dest = new File(filePath + fileName);
String imgString = "/upload/" + fileName;
// 判断文件是否存在
if (!dest.getParentFile().exists()) {
// 不存在就创建一个
dest.getParentFile().mkdirs();
}
try {
// 上传
file.transferTo(dest);
return AjaxResult.success("上传成功", imgString);
} catch (Exception e) {
e.printStackTrace();
return AjaxResult.error("上传失败");
}
}
@PostMapping("/uploads")
public AjaxResult uploadFiles(@RequestParam("files") MultipartFile[] files) {
String img = "";
//获取jar包所在目录
ApplicationHome h = new ApplicationHome(getClass());
File jarF = h.getSource();
//在jar包所在目录下生成一个upload文件夹用来存储上传的图片
String filePath = uppath+ "/upload/";
File fileDir = new File(filePath);
if (!fileDir.exists() && !fileDir.isDirectory()) {
fileDir.mkdirs();
}
if (files != null && files.length > 0) {
for (int i = 0; i < files.length; i++) {
String OriginalFilename = files[i].getOriginalFilename();
System.out.println("文件名为:" + OriginalFilename);
String fileName = System.currentTimeMillis() + "." + OriginalFilename.substring(OriginalFilename.lastIndexOf(".") + 1);
File dest = new File(filePath + fileName);
imgString = "/upload/" + fileName;
try {
files[i].transferTo(dest);
if (img.equals("")) {
img = imgString;
} else {
img = img + ";" + imgString;
}
} catch (IOException e) {
e.printStackTrace();
return AjaxResult.warn(e.getMessage());
}
}
} else {
return AjaxResult.warn("文件为0");
}
return AjaxResult.success("上传成功", img);
}
}
package com.lostperson.config;
import com.lostperson.interceptor.AuthenticationInterceptor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
@Configuration
public class WebConfig extends WebMvcConfigurationSupport {
@Value("${image.uploadurl}")
private String uppath;
@Override
protected void addInterceptors(InterceptorRegistry registry) {
// 拦截所有请求,通过判断是否有 @LoginRequired 注解 决定是否需要登录
registry.addInterceptor(authenticationInterceptor())
.addPathPatterns("/admin/**","/getInfo");
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
// registry.addResourceHandler("/**").addResourceLocations(
// "classpath:/static/");
registry.addResourceHandler("/upload/**").addResourceLocations(
"file:"+uppath+"/upload/");
}
/**
* 跨越配置
* 改用过滤器CorsFilter 来配置跨域,由于Filter的位置是在Interceptor之前的,问题得到解决:
*/
@Bean
public CorsFilter corsFilter() {
CorsConfiguration config = new CorsConfiguration();
// 设置允许跨域请求的域名
config.addAllowedOrigin("*");
// 是否允许证书 不再默认开启
// config.setAllowCredentials(true);
// 设置允许的方法
config.addAllowedMethod("*");
// 允许任何头
config.addAllowedHeader("*");
config.addExposedHeader("Authorization");
UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource();
configSource.registerCorsConfiguration("/**", config);
return new CorsFilter(configSource);
}
@Bean
public AuthenticationInterceptor authenticationInterceptor() {
return new AuthenticationInterceptor();
}
}