1.idea建立单独文件管理模块source-center
2.更新 pom 依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="#34;
xmlns:xsi="#34;
xsi:schemaLocation=" #34;>
<parent>
<artifactId>cevent-source-cloudcenter</artifactId>
<groupId>cevent.source.cloudcenter</groupId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>source-center</artifactId>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.4.3</version>
</dependency>
<!--继承 mybatis -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!--集成热部署-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
<!--集成server-common模块-->
<dependency>
<groupId>cevent.source.cloudcenter</groupId>
<artifactId>server-common</artifactId>
</dependency>
</dependencies>
</project>
3.配置properties端口及应用名+logback.xml
spring.application.name=source-center
server.port=8803
eureka .client.service-url.defaultZone=
server.servlet.context-path=/source
4.springboot启动类
package cevent.source.cloudcenter.source.config;/**
* Created by Cevent on 2021/4/23.
*/
import org.mybatis.spring. annotation .MapperScan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.core.env.Environment;
/**
* @author cevent
* @description 文件资源管理服务中心
* @date 2021/4/23 16:37
*/@SpringBootApplication
@EnableEurekaClient
@MapperScan(value = {"cevent.source.cloudcenter.server.mapper"})
@ComponentScan("cevent.source.cloudcenter")
public class SourceCenterApplication {
private static final Logger LOG= LoggerFactory.getLogger(SourceCenterApplication.class);
public static void main(String[] args) {
SpringApplication springApplication=new SpringApplication(SourceCenterApplication.class);
Environment environment=springApplication.run(args).getEnvironment();
LOG.info("文件资源中心模块source-center启动");
LOG.info("source-center地址:t{}",environment.getProperty("server.port"));
}
}
5.vue前端上传页面-单图
1)element中,默认隐藏了input,需要配置display
<el-form-item label="头像" prop="icon">
<input id=" Upload -source- File " class="iconInput" type="file" v-on:change="uploadSource()" />
</el-form-item>
uploadSource(){
//表单方式提交数据
let formData=new window.FormData();
//获取input中选择file
let icon=document.querySelector('#upload-source-file').files[0];
console.log('上传的icon:',icon);
//key和后端请求的参数名一致
formData.append('file',icon);
Loadings.show();
this.$axios.post(process.env.VUE_APP_SERVER + '/source/admin/upload/icon',formData)
.then((response)=>{
Loadings.hide();
resp=response.data;
});
}
//更新样式
[data-v-53b3b518] input[type=file]{
display: block;
}
2)后端:controller更新测试方法
package cevent.source.cloudcenter.source.controller.admin;/**
* Created by Cevent on 2021/4/24.
*/
import cevent.source.cloudcenter.server.dto.ResponseDataDto;
import cevent.source.cloudcenter.server.util.UUID8Util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation. Request Mapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java .io.File;
import java.io.IO Exception ;
/**
* @author cevent
* @description 文件上传:单图
* @date 2021/4/24 14:41
*/@RestController
@RequestMapping("/admin")
public class UploadIconController {
private static final Logger LOG= LoggerFactory.getLogger(UploadIconController.class);
public static final String BUSINESS_NAME="文件上传模块";
/*1.单图上传:
@RequestParam:基于文件是formData形式传输
MultipartFile:富文本大文件
file:formData.append('file',icon),前端formData中提交file参数名,包含元素查询中的icon文件
*/ @RequestMapping("/test")
public String test(){
return "文件系统模块启动成功";
}
@RequestMapping("/upload/icon")
public ResponseDataDto uploadIcon(@RequestParam MultipartFile file) throws IOException {
LOG.info("上传的文件file:{}",file);
LOG.info("上传的文件file名fileName:{}",file.getOriginalFilename());
LOG.info("上传的文件file大小:{}",file.getSize());
LOG.info("上传的文件file名name:{}",file.getName());
//保存文件到本地
String fileName=file.getOriginalFilename();
String fileKey= UUID8Util.getShortUUID();
String fullPath="D:/DEV_CODE/Intelligy_idead_code/upload-file/source/"+fileKey+"-"+fileName;
File dest=new File(fullPath);
file.transferTo(dest);
LOG.info("获取destination目的位置完全路径:{}",dest.getAbsolutePath());
ResponseDataDto responseData=new ResponseDataDto();
responseData.setResponseData("#34;+fileKey+"-"+fileName);
return responseData;
}
}
6.前端请求图片回显路径
Config中配置静态资源/f/**前端请求路径
package cevent.source.cloudcenter.source.config;/**
* Created by Cevent on 2021/4/24.
*/
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandler registry ;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* @author cevent
* @description springMVC静态资源配置,暴露外部文件目录
* @date 2021/4/24 16:55
*/@Configuration
public class SourceStaticConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
/** pathPatterns:所有带/f ...**的请求,为静态资源请求=D:/DEV_CODE/Intelligy_idead_code/upload-file/
* 请求时保存的去全路径:String fullPath="D:/DEV_CODE/Intelligy_idead_code/upload-file/source/"+fileKey+"-"+fileName;
* 访问图片全路径(加入请求的source目录):
*/ registry.addResourceHandler("/f/**").addResourceLocations("file:D:/DEV_CODE/Intelligy_idead_code/upload-file/");
}
}
7.更新properties中配置file的路径及get路径
spring.application.name=source-center
server.port=8803
eureka.client.service-url.defaultZone=
server.servlet.context-path=/source
#图片上传位置,在controller中@Value("${file.*}")
file.targetPath=D:/DEV_CODE/Intelligy_idead_code/upload-file/
file.getPath=
8.Controller实现
package cevent.source.cloudcenter.source.controller.admin;/**
* Created by Cevent on 2021/4/24.
*/
import cevent.source.cloudcenter.server.dto.ResponseDataDto;
import cevent.source.cloudcenter.server.util.UUID8Util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
/**
* @author cevent
* @description 文件上传:单图
* @date 2021/4/24 14:41
*/@RestController
@RequestMapping("/admin")
public class UploadIconController {
private static final Logger LOG= LoggerFactory.getLogger(UploadIconController.class);
public static final String BUSINESS_NAME="文件上传模块";
//注入properties中的file配置
@Value("${file.targetPath}")
private String FILE_TARGET_PATH;
@Value("${file.getPath}")
private String FILE_GET_PATH;
/*1.单图上传:
@RequestParam:基于文件是formData形式传输
MultipartFile:富文本大文件
file:formData.append('file',icon),前端formData中提交file参数名,包含元素查询中的icon文件
*/ @RequestMapping("/test")
public String test(){
return "文件系统模块启动成功";
}
@RequestMapping("/upload/icon")
public ResponseDataDto uploadIcon(@RequestParam MultipartFile file) throws IOException {
LOG.info("上传的文件file:{}",file);
LOG.info("上传的文件file名fileName:{}",file.getOriginalFilename());
LOG.info("上传的文件file大小:{}",file.getSize());
LOG.info("上传的文件file名name:{}",file.getName());
LOG.info("上传的文件file类型:{}",file.getContentType());
//保存文件到本地
String fileName=file.getOriginalFilename();
String fileKey= UUID8Util.getShortUUID();
String fullPath=FILE_TARGET_PATH+"source/"+fileKey+"-"+fileName;
File dest=new File(fullPath);
file.transferTo(dest);
LOG.info("获取destination目的位置完全路径:{}",dest.getAbsolutePath());
ResponseDataDto responseData=new ResponseDataDto();
responseData.setResponseData(FILE_GET_PATH+"f/source/"+fileKey+"-"+fileName);
return responseData;
}
}
9.静态资源配置SourceStaticConfig
package cevent.source.cloudcenter.source.config;/**
* Created by Cevent on 2021/4/24.
*/
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* @author cevent
* @description springMVC静态资源配置,暴露外部文件目录
* @date 2021/4/24 16:55
*/@Configuration
public class SourceStaticConfig implements WebMvcConfigurer {
//注入properties中的file配置
@Value("${file.targetPath}")
private String FILE_TARGET_PATH;
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
/** pathPatterns:所有带/f ...**的请求,为静态资源请求=D:/DEV_CODE/Intelligy_idead_code/upload-file/
* 请求时保存的去全路径:String fullPath="D:/DEV_CODE/Intelligy_idead_code/upload-file/source/"+fileKey+"-"+fileName;
* 访问图片全路径(加入请求的source目录):
*/ registry.addResourceHandler("/f/**").addResourceLocations("file:"+FILE_TARGET_PATH);
}
}
10.前端页面显示-employee页面
<el-table-column
sortable
fixed
prop="icon"
label="头像"
width="60"
:show-overflow-tooltip="true"
>
<template slot-scope="scope">
<!--<el-avatar v-if="!employee.icon" src="../../imgs/logo300-1.png"></el-avatar>-->
<el-avatar :src="scope.row.icon" ></el-avatar>
</template>
</el-table-column>
11.前端页面显示-addEmployee页面
<!--
action:必选参数,上传的地址,可以为空
:show-file-list:是否显示已上传文件列表
img-responsive:图片属性为响应式
-->
<el-form-item label="头像" prop="icon">
<input id="upload-source-file" class="iconInput" type="file" v-on:change="uploadSource()" />
<el-row>
<el-col :span="2">
<img :src="employee.icon" class="img-responsive" />
</el-col>
</el-row>
<!--<el-upload id="upload-source-file"
class="avatar-uploader"
action=""
:show-file-list="false"
:on-success="handleAvatarSuccess"
:before-upload="beforeAvatarUpload"
:on-change="uploadSource">
<img v-if="employee.icon" :src="employee.icon" class="avatar">
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>-->
</el-form-item>
uploadSource(){
//表单方式提交数据
let formData=new window.FormData();
//获取input中选择file
let icon=document.querySelector('#upload-source-file').files[0];
console.log('上传的icon:',icon);
//key和后端请求的参数名一致
formData.append('file',icon);
Loadings.show();
this.$axios.post(process.env.VUE_APP_SERVER + '/source/admin/upload/icon',formData)
.then((response)=>{
Loadings.hide();
let resp=response.data;
if(resp.success){
console.log("上传到的responseData头像地址:",resp.responseData);
this.employee.icon=resp.responseData;
}
});
}
12.文件上传完整功能图解
注意,在elementUI中,调用el-form, 每个item会默认将默认的input的display=none ,需要更改原属性 display=block
为增加用户体验 ,我们需要隐藏掉这个input更换为 button 按钮,但我们不能隐藏
只能将这个input的位置移动到用户视口看不到的位置
13.文件上传组件开发
FileIcon组件
<template>
<div>
<el-button class="upload-btn" type="primary" @click="selectFile">{{uploadTile}}
<i class="upload-li el-file-upload el-file--left"></i>
</el-button>
<input :id="inputId+'-file'" ref="file" class="fileInput" type="file" v-on:change="uploadSource()" />
</div>
</template>
<script>
export default {
name: "FileIcon",
//暴露出可配置的属性
props:{
//暴露按钮标题
uploadTile:{
default:'上传文件'
},
//暴露页面中的inputId
inputId:{
default:'upload-source'
},
//暴露页面传入的文件类型
suffixType:{
default:[]
},
//回调函数,组件中没有employee对象
afterUpload:{
type:Function,
default: null
}
},
data:function () {
return{}
},
methods:{
selectFile(){
//trigger:联动input按钮点击
console.log("进入方法?")
$("#"+this.inputId+"-file").trigger("click");
},
uploadSource(){
//表单方式提交数据
let formData=new window.FormData();
//通过别名获取file,不需要id
let file=this.$refs.file.files[0];
//file类型判断["jpg","jpeg","png","gif"]
let suffixType=this.suffixType;
let fileName=file.name;
//查询到包含.的索引位置+1,substring提取字符串中介于两个指定下标之间的字符,length-(indexof+1) 转换为小写
let suffix=fileName.substring(fileName.lastIndexOf(".")+1,fileName.length).toLowerCase();
//定义后缀校验变量
let validateSuffix=false;
//循环后缀类型
for(let i=0;i<suffixType.length;i++){
if(suffixType[i].toLowerCase()===suffix){
validateSuffix=true;
break;
}
}
if(!validateSuffix){
toast.warning("文件格式不正确,只支持上传:"+suffixType.join(",")+"文件");
//在拦截后,避免onchange事件不触发,需要清空id标签
$("#"+this.inputId+"-file").val("");
return;
}
//获取input中选择file
console.log('上传的File:',file);
//key和后端请求的参数名一致
formData.append('file',file);
Loadings.show();
this.$axios.post(process.env.VUE_APP_SERVER + '/source/admin/upload/icon',formData)
.then((response)=>{
Loadings.hide();
let resp=response.data;
//将获取的resp放入回调,传到页面
this.afterUpload(resp);
console.log("组件发送到页面的resp图片地址:",resp.responseData);
//避免on-change事件在第二次相同类型点击后,不触发,将id对应标签设置为空
$("#"+this.inputId+"-file").val("");
});
},
}
}
</script>
<style scoped>
.fileInput{
margin-left: -300px;
color: white;
z-index: -1;
}
.upload-btn{
float: left;
margin-right: 100%;
margin-bottom: 10px;
padding: 8px 8px;
}
.upload-li{
font-size: 20px;
}
</style>
addEmployee页面
<!--
action:必选参数,上传的地址,可以为空
:show-file-list:是否显示已上传文件列表
在el中,input不可以设置为none,否则无法响应点击事件
img-responsive:图片属性为响应式
FileIcon绑定了props中有inputId:{default:''},那么这里可以绑定一个input-id=" '注意绑定的值需要+引号' "
-->
<el-form-item class="upload-icon-area" label="头像" prop="icon">
<file-icon :upload-tile="'上传头像'" :input-id="'upload-icon'" :suffix-type="['jpg','jpeg','png','gif']"
:after-upload="afterUpload"></file-icon>
<el-row class="upload-icon">
<el-col :span="2">
<img :src="employee.icon" class="img-responsive" />
</el-col>
</el-row>
<!--<el-upload id="upload-source-file"
class="avatar-uploader"
action=""
:show-file-list="false"
:on-success="handleAvatarSuccess"
:before-upload="beforeAvatarUpload"
:on-change="uploadSource">
<img v-if="employee.icon" :src="employee.icon" class="avatar">
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>-->
</el-form-item>
....script...
//接收文件上传组件传入的resp
afterUpload(resp){
if(resp.success){
console.log("上传到的responseData头像地址:",resp.responseData);
this.employee.icon=resp.responseData;
}
}
...css...
[data-v-53b3b518] input[type=file]{
display: block;
}
.upload-icon{
margin-top: -50px;
margin-bottom: 10px;
}
gitee提交, 源码开放 , 长期维护 , 欢迎fork ,关注,mark, 点赞 , 收藏 , 转发
gitee地址: