注意:该项目中涉及到读取配置文件
- 一、读取配置文件
- 1、配置文件监听器
package com.**.productcenter.config;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.ApplicationListener;
/**
* 配置文件加载监听器
* @author Zyred
*/
public class PropertiesListener implements ApplicationListener<ApplicationStartedEvent> {
/**
* 配置项名称 key
*/
private String propertyFileName;
/**
* 构造器
* @param name
*/
public PropertiesListener(String name) {
this.propertyFileName = name;
}
@Override
public void onApplicationEvent(ApplicationStartedEvent applicationStartedEvent) {
PropertiesListenerConfig.loadAllProperties(propertyFileName);
}
}
- 2、配置文件读取
package com.**.productcenter.config;
import org.springframework.beans.BeansException;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
/**
* 读取配置文件
* @author Zyred
*/
public class PropertiesListenerConfig {
/**
* 定义属性集合
*/
public static Map propertiesMap = new HashMap();
/**
* 加载配置文件
* @param props
* @throws BeansException
*/
private static void processProperties(Properties props) throws BeansException {
propertiesMap = new HashMap<String, String>();
for (Object key : props.keySet()) {
String keyStr = key.toString();
try {
// PropertiesLoaderUtils的默认编码是ISO-8859-1,在这里转码一下
propertiesMap.put(keyStr, new String(
props.getProperty(keyStr).getBytes("ISO-8859-1"), "utf-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (java.lang.Exception e) {
e.printStackTrace();
}
}
}
/**
* 加载配置文件
* @param propertyFileName
*/
public static void loadAllProperties(String propertyFileName) {
try {
Properties properties = PropertiesLoaderUtils.loadAllProperties(propertyFileName);
processProperties(properties);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 根据属性获取配置项
* @param name
* @return
*/
public static String getProperty(String name) {
return propertiesMap.get(name) + "";
}
/**
* 获取所有配置项
* @return
*/
public static Map<String, String> getAllProperty() {
return propertiesMap;
}
}
- 3、修改启动类
package com.**.productcenter;
import com.kedi.productcenter.config.PropertiesListener;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.ComponentScan;
/**
* 方法实现说明 商品中心 启动类
* @author ytw
* @param
* @return
* @exception
* @update Zyred 修改启动项,加载读取配置文件的方法
* @date 2019/7/22 16:17
*/
@ComponentScan("com.kedi")
@EnableEurekaClient
@SpringBootApplication
public class ProductCenter {
public static void main( String[] args ) {
SpringApplication application = new SpringApplication(ProductCenter.class);
application.addListeners(new PropertiesListener("file.properties"));
application.run(args);
}
}
- 二、文件上传
- 书写工具类
package com.**.productcenter.utils;
import com.kedi.productcenter.config.PropertiesListenerConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.util.UUID;
/**
* 文件上传方法, 该类可以传 视频, 文件, 音频, 图片
* @author Zyred
*/
public class FileUploadUtil {
Logger logger = LoggerFactory.getLogger(FileUploadUtil.class);
private String type;
private MultipartFile file;
private String savePath;
/**
* 文件访问地址
*/
private String resultPath;
/**
* 根据类型读取配置文件构造器
* @param type properties文件key
* @param file 文件
*/
public FileUploadUtil(String type, MultipartFile file){
this.file = file;
this.type = type;
}
/**
* 根据保存路径构造器
* @param file 文件
* @param savePath 保存路径如: C:\\upload
*/
public FileUploadUtil(MultipartFile file, String savePath){
this.file = file;
this.savePath = savePath;
}
/**
* 上传文件方法
* @return
*/
public String uploadFile(){
logger.info("上传文件类型:" + type);
String save_path = null;
InputStream is = null;
FileOutputStream os = null;
//判断文件不为空
if (file == null && file.isEmpty()) {
return "上传的文件为空";
}
if(type != null && !type.isEmpty()){
//通过key获取到存储的路径
save_path = PropertiesListenerConfig.getProperty(type);
}
if(save_path == null){
save_path = savePath;
}
//获取到文件的名字
String oldFileName = file.getOriginalFilename();
logger.info("上传文件名称:" + oldFileName);
String oldFileNameSufix = oldFileName.substring(oldFileName.lastIndexOf("."), oldFileName.length());
//得到文件的新名字
String newFileName = UUID.randomUUID().toString() + oldFileNameSufix;
logger.info("上传文件新名称:" + newFileName);
//保存后的文件路径
String affterPath = save_path + newFileName;
logger.info("文件保存位置:" + affterPath);
//创建文件对象
File dest = new File(affterPath);
//文件或目录是否存在
if (dest.exists()) {
dest.mkdir();
}
//判断文件父目录是否存在
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdir();
}
//保存文件
try {
//获取输入流
is = file.getInputStream();
//创建输出流
os = new FileOutputStream(dest);
int len = 0;
byte[] buffer = new byte[2048*512];
//往输出流中写入字节流
while ((len = is.read(buffer)) != -1) {
os.write(buffer, 0, len);
}
InetAddress localHost = InetAddress.getLocalHost();
//请求前缀 http:// https://
String prefix = PropertiesListenerConfig.getProperty("file.download.path.prefix");
//java项目请求路径 如:/image/download/file
String middle = PropertiesListenerConfig.getProperty("file.download.path.middle");
resultPath = prefix + localHost.getHostAddress() + middle + newFileName;
logger.info("文件下载地址:" + resultPath);
} catch (IOException e) {
e.printStackTrace();
return "服务器异常,请稍后重试";
}finally {
try{
if(os != null || os != null){
os.close();
os.flush();
is.close();
}
}catch (IOException e){
e.printStackTrace();
return "流关闭异常";
}
}
return resultPath;
}
}
- 2、controller方法
package com.**.productcenter.controller;
import com.kedi.productcenter.config.PropertiesListenerConfig;
import com.kedi.productcenter.utils.FileUploadUtil;
import com.kedi.productcenter.utils.ResultVoUtil;
import com.kedi.productcenter.vo.ResultVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.util.UUID;
/**
* 图片, 文件, 视频, 音频上传共用接口
* @author Zyred
*/
@Controller
@RequestMapping("/file")
public class FileUploadUtilController {
@RequestMapping("/index")
public String file(){
return "index";
}
/**
* 文件上传
* @param type
* @return
*/
@ResponseBody
@RequestMapping(value = "/fileUpload/ds", produces="application/json;charset=UTF-8", method = RequestMethod.POST)
public String fileUpload(@RequestParam("type") String type, @RequestParam("file") MultipartFile file){
FileUploadUtil upload = new FileUploadUtil(type, file);
String result = upload.uploadFile();
return result;
}
}
- 3、修改配置文件
spring: servlet: multipart: max-file-size: 1024MB # 允许上传最大文件大小 file-size-threshold: 1MB max-request-size: 1024MB # 设置最大的请求文件的大小
最后,如果项目中使用了zuul作为网关,在配置文件中也要加上该配置