文件管理
VUE
创建vue
vue create ***
npm i element-ui -S
npm i axios -S
main.js
import Vue from 'vue'
import App from './App.vue'
import router from './router'
Vue.config.productionTip = false
new Vue({
router,
render: h => h(App)
}).$mount('#app')
引入main.js
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
//
Vue.use(ElementUI);
输出
export default {
name:'***',
data(){
return{
}
},
methods: {
}
}
前端
分页
<!-----分页----->
<el-row type="flex" align="bottom" style="background-color: white;height:40px;">
<el-col :span="24">
<el-pagination
@size-change="handleSizeChange"
@current-change="handleCurrentChange"
:current-page="pageNum"
:page-sizes="[10, 20, 50, 100]"
:page-size="pageSize"
layout="total, sizes, prev, pager, next, jumper"
:total="total">
</el-pagination>
</el-col>
</el-row>
<!--分页结束------------------------------------->
//分页
handleSizeChange(pageSize) {
this.pageSize = pageSize
this.load()
},
handleCurrentChange(pageNum) {
this.pageNum = pageNum
this.load()
},
axios.js封装
import axios from "axios"
import router from "./router"
import Element from "element-ui"
axios.defaults.baseURL = "http://localhost:8081" //前端端口
const request = axios.create({
timeout: 5000,
headers: {
'Content-Type': "application/json; charset=utf-8"
}
})
request.interceptors.request.use(config => {
config.headers['Authorization'] = localStorage.getItem("token");
return config;
})
//设置全局拦截
request.interceptors.response.use(response => {
let res = response.data;
if (response.config.responseType === 'blob') {
return res
}
if (typeof res === 'string') {
res = res ? JSON.parse(res) : res
return res;
}
if (res.code === 200) {
return response; //状态码正常,返回正常结果
} else {
Element.Message.error(!res.msg ? '系统异常' : res.msg);
return Promise.reject(response.data.msg); //拒绝往前走
}
}, error => {
if (error.response.data) {
error.message = error.response.data.msg;
}
if (error.response.status === 401) {
router.push("/login");
}
Element.Message.error(error.message, {duration: 3000});
return Promise.reject(error);
})
export default request
随后到main.js文件中配置
import axios from "./axios" //引用
Vue.prototype.$axios = axios //全局可以使用axios的库
后端
application.yml配置
serveexport default requestr:
port: 9090
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/qing?serverTimezone=GMT%2b8
username: root
password: 123456
mybatis:
mapper-locations: classpath:mapper/*.xml #扫描所有mybatis的xml文件
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
Springboot跨域设置
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;
@Configuration
public class CorsConfig {
// 当前跨域请求最大有效时长。这里默认1天
private static final long MAX_AGE = 24 * 60 * 60;
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("http://localhost:8080"); // 1 设置访问源地址,前端端口
corsConfiguration.addAllowedHeader("*"); // 2 设置访问源请求头
corsConfiguration.addAllowedMethod("*"); // 3 设置访问源请求方法
corsConfiguration.setMaxAge(MAX_AGE);
source.registerCorsConfiguration("/**", corsConfiguration); // 4 对接口配置跨域设置
return new CorsFilter(source);
}
}
分页查询接口
/**
* 分页查询接口
*
* @param
* @return
*/
@GetMapping("/page")
public Result findPage(String name, String type) {
// System.out.println(name);
// System.out.println(type);
QueryWrapper<Files> queryWrapper = new QueryWrapper<Files>().like(StrUtil.isNotBlank(name), "name", name).eq(StrUtil.isNotBlank(type), "type", type)
.eq("is_delete", false);
Page<Files> page = this.filesService.page(getPage(), queryWrapper);
return Result.succ(page);
}
Mybatis-Plus拦截器配置
@Configuration
@MapperScan("com.wisdompark.mapper,com.wisdompark.mapper.wechat")
public class MybatisPlusConfig {
/**
* 分页插件,一缓和二缓遵循mybatis机制
* 需设置 MybatisConfiguration#useDeprecatedExecutor = false 避免缓存出现问题(该属性会在旧插件移除后一同移除)
*/
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor(){
//新的分页插件
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
//防止全表更新
interceptor.addInnerInterceptor(new BlockAttackInnerInterceptor());
return interceptor;
}
@Bean
public ConfigurationCustomizer configurationCustomizer() {
return configuration -> configuration.setUseDeprecatedExecutor(false);
}
}
文件上传接口
//application配置上传路径
files:
upload:
path: D:\disk\files\
//配置好的路径
@Value("${files.upload.path}")
private String fileUploadPath;
@Autowired
private FileslistMapper fileMapper;
/**
* 文件上传接口
*
* @param file 前端传递过来的文件
* @return
* @throws IOException
*/
@PostMapping("/upload")
public String upload(@RequestParam MultipartFile file, HttpServletRequest req) throws IOException {
String originalFilename = file.getOriginalFilename();
String type = FileUtil.extName(originalFilename);
long size = file.getSize();
// 定义一个文件唯一的标识码
String uuid = IdUtil.fastSimpleUUID();
String fileUUID = uuid + StrUtil.DOT + type;
//先存到磁盘上
File uploadFile = new File(fileUploadPath + fileUUID);
// 判断配置的文件目录是否存在,若不存在则创建一个新的文件目录
File parentFile = uploadFile.getParentFile();
if (!parentFile.exists()) {
parentFile.mkdirs();
}
file.transferTo(uploadFile);
Date currentTime = new Date();
SimpleDateFormat time = new SimpleDateFormat("yyyy-MM-dd HH:mm");
String url = "http://localhost:8081/file/download/" + fileUUID;
String preview_url = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + "/" + fileUUID;
//存储数据库
Files saveFile = new Files();
saveFile.setName(originalFilename);
saveFile.setSize(size / 1024);
saveFile.setType(type);
saveFile.setTime(time.format(currentTime));
saveFile.setUrl(url);
saveFile.setPreviewUrl(preview_url);
fileMapper.insert(saveFile);
return url;
}
文件下载接口
/**
* 文件下载接口 http://localhost:8081/file/download/{fileUUID}
*
* @param fileUUID
* @param response
* @throws IOException
*/
@GetMapping("/download/{fileUUID}")
public void download(@PathVariable String fileUUID, HttpServletResponse response) throws IOException {
// 根据文件的唯一标识码获取文件
File uploadFile = new File(fileUploadPath + fileUUID);
ServletOutputStream os = response.getOutputStream();
//设置输出流的格式
response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileUUID, "UTF-8"));
//写出
response.setContentType("application/octet-stream");
// 读取文件的字节流
os.write(FileUtil.readBytes(uploadFile));
os.flush();
os.close();
}
文件预览接口
/**
* 文件预览,pdf
* @param response
*/
@GetMapping(value = "/preview/{fileUUID}")
public void view(@PathVariable String fileUUID, HttpServletResponse response) {
// 根据文件的唯一标识码获取文件
File uploadFile = new File(fileUploadPath + fileUUID);
//String filePath = "D:/disk/files/f42876083da6492e9901db07d00833b1.pdf"; // 本该根据ID去数据库查,这里是hard code
// 设返回的contentType
response.setContentType("application/pdf"); // 不同文件的MimeType参考后续链接
// 读取路径下面的文件
try {
FileCopyUtils.copy(new FileInputStream(uploadFile), response.getOutputStream());
} catch (Exception e) {
e.printStackTrace();
}