配置文件配置baseUrl
文件 params.properties配置,此路径的绝对路径为:E:/home/gscq073240j/myfile/temp_qbs5/ (E盘为项目所在的磁盘)
在初始化类中配置不同文件保存的不同的文件夹
@Component
@PropertySource("classpath:conf/params.properties")
public class FileUploadPathConfig {
@Value("${baseFilePath}")
String basePath;
public static String UPLOAD_PATH = null;
public static String IMG_PATH = null;
public static String VIDEO_PATH = null;
public static String AUDIO_PATH = null;
public static String TYPE_PATH = null;
public static String EXCEL_PATH = null;
public static String TYPE_TEMPLATE = null;
public static String QUESTION_PATH = null;
public static String QUESTION_EXCEL_PATH = null;
public static String QUESTION_EXCEL_TEMPLATE = null;
public static String QUESTION_EXCEL_TEMP_PATH = null;
public static String QUESTION_FILE = null;
@PostConstruct
void init() {
UPLOAD_PATH = basePath;
IMG_PATH = UPLOAD_PATH + "img/";
VIDEO_PATH = UPLOAD_PATH + "video/";
AUDIO_PATH = UPLOAD_PATH + "audio/";
TYPE_PATH = UPLOAD_PATH + "type/";
EXCEL_PATH = TYPE_PATH + "excel/";
TYPE_TEMPLATE = TYPE_PATH + "type_template__.xls";
QUESTION_PATH = UPLOAD_PATH + "question/";
QUESTION_EXCEL_PATH = QUESTION_PATH + "excel/";
QUESTION_EXCEL_TEMPLATE = QUESTION_EXCEL_PATH + "question_template__.xlsx";
QUESTION_EXCEL_TEMP_PATH = QUESTION_EXCEL_PATH + "temp/";
QUESTION_FILE = QUESTION_PATH + "file/";
}
}
配置之后图片的保存路径为:/home/gscq073240j/myfile/temp_qbs5/img/
图片上传接口:
@ResponseBody
@PostMapping(value = "/fileUpload")
public Result fileUpload(@RequestParam(value = "file") MultipartFile file, HttpServletRequest request) {
File aa = new File(FileUploadPathConfig.IMG_PATH ) ;
if (!new File(FileUploadPathConfig.IMG_PATH).exists()){
new File(FileUploadPathConfig.IMG_PATH).mkdirs();
}
if (file.isEmpty()) {
return ResultFactory.buildFailResult("文件为空");
}
String filePath = null, returnPath = null, suffixName = null;
try {
byte[] b = new byte[4];
file.getInputStream().read(b, 0, b.length);
String type = bytesToHexString(b).toUpperCase();
if (type.contains("0000001C") || type.contains("00000020")) {
//视频文件
filePath = FileUploadPathConfig.VIDEO_PATH;
returnPath = "/upload/video/";
suffixName = ".mp4";
} else if (type.contains("FFD8FFE0")) {
// 图片格式
filePath = FileUploadPathConfig.IMG_PATH;
returnPath = "/upload/img/";
BufferedImage image = ImageIO.read(file.getInputStream());
if (image != null) {
if (image.getWidth() == 0) {
return ResultFactory.buildFailResult("图片格式不规范!");
}
if (file.getSize() > 1 * 1024 * 200) {
return ResultFactory.buildFailResult("小于200KB的照片才允许上传!");
}
} else {
return ResultFactory.buildFailResult("图片格式不规范!");
}
suffixName = ".jpg";
} else if (type.contains("49443304")) {
// 音频文件
filePath = FileUploadPathConfig.AUDIO_PATH;
returnPath = "/upload/audio/";
suffixName = ".mp3";
} else {
return ResultFactory.buildFailResult("不支持上传文件格式");
}
} catch (IOException e) {
e.printStackTrace();
}
String fileContentType = file.getContentType();
String fileName = file.getOriginalFilename(); // 文件名
// suffixName = fileName.substring(fileName.lastIndexOf(".")); // 后缀名
fileName = UUID.randomUUID() + suffixName; // 新文件名
String absolutePath = new File(filePath).getAbsolutePath();
File dest = new File(new File(filePath).getAbsolutePath()+"/"+ fileName);
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdirs();
}
// FileOutputStream out = new FileOutputStream(fileName);
// out.write(file.getBytes());
// out.flush();
// out.close();
try {
file.transferTo(dest);
} catch (IOException e) {
e.printStackTrace();
return ResultFactory.buildFailResult(e.getMessage());
}
return ResultFactory.buildSuccessResult(returnPath + fileName);
}
返回的图片路径为 //upload/img/+uuid的值.jpg ,但是实际图片存放的路径为E:/home/gscq073240j/myfile/temp_qbs5/img/uuid的值.jpg.
项目的页面样式为
图片此时的回显
访问的路径如上图。
所以需要配置静态资源访问路径:
@Configuration
public class SpringWebMvcConfigurer extends WebMvcConfigurationSupport {
/**
* 配置静态访问资源
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
/* String p = new File(path).getAbsolutePath() + File.separator;//取得在服务器中的绝对路径
System.out.println("Mapping /upload/** from " + p);
registry.addResourceHandler("/upload/**") // 外部访问地址
.addResourceLocations("file:" + p)// springboot需要增加file协议前缀
.setCacheControl(CacheControl.maxAge(30, TimeUnit.MINUTES));// 设置浏览器缓存30分钟*/
// 覆盖默认配置,自定义
registry.addResourceHandler("/upload/**").addResourceLocations("file:"+ FileUploadPathConfig.UPLOAD_PATH);
registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/", "classpath:/static/static/");
super.addResourceHandlers(registry);
}
}
此时图片就能回显了。
添加用户,保存包数据库
控制层:
/**
* 新增专家用户
* @param userModel
* @return
*/
@RequestMapping(value = "/addUser")
@ResponseBody
public Result addUser(@RequestBody UserModel userModel) {
return userService.addUser(userModel);
}
service层
@Override
@Transactional(rollbackFor = Exception.class)
public Result addUser(@RequestBody UserModel userModel) {
UserEntity userEntity = userModel.prototype(); //model类转实体类
try {
userEntity.setCardIdPath(FileUtils.nomenclator(userEntity.getCardId(),
FileUploadPathConfig.IMG_PATH + userEntity.getCardIdPath().replace(userModel.getBaseUrl(),
""), UserEntity.CARDID_FRONT));
userEntity.setCardIdPathBack(FileUtils.nomenclator(userEntity.getCardId(),
FileUploadPathConfig.IMG_PATH + userEntity.getCardIdPathBack().replace(userModel.getBaseUrl(),
""), UserEntity.CARDID_BACK));
userEntity.setProfessionalPath(FileUtils.nomenclator(userEntity.getCardId(),
FileUploadPathConfig.IMG_PATH + userEntity.getProfessionalPath().replace(userModel.getBaseUrl(),
""), UserEntity.PROFESSIONAL));
userEntity.setQualificationCertificatePath(FileUtils.nomenclator(userEntity.getCardId(),
FileUploadPathConfig.IMG_PATH + userEntity.getQualificationCertificatePath().replace(userModel.getBaseUrl(),
""), UserEntity.QUALIFICATION));
} catch (IOException e) {
e.printStackTrace();
}
userMapper.insertSelective(userEntity);
return ResultFactory.buildSuccessResult(null);
}
nomenclator 方法
将存入数据库的值/upload/img/uuid的值.jpg改为/upload/img/身份证号.jpg,并将文件夹中实际的图片的文件名renameto(文件移动)为身份证号.jpg
public class FileUtils {
public static String nomenclator(String cardId, String path, String name) throws IOException {
String replace = path.replace("/upload/img/", "");
File file = new File(replace);
if (!file.exists()) {
file.createNewFile();
}
String parent = file.getParent(); //根路径
String suffixName = file.getName().substring(file.getName().lastIndexOf("."));
String s = parent + File.separator + cardId + "_" + name + suffixName;
File newFile = new File(s);
if (newFile.exists() && newFile.isFile()) {
newFile.delete();
}
File f = new File(s);
if (file.renameTo(f)) {
String aa = "/upload/img/" + f.getName();
return "/upload/img/" + f.getName();
}
return null;
}
}