配置文件配置baseUrl
文件 params.properties配置,此路徑的絕對路徑為:E:/home/gscq073240j/myfile/temp_qbs5/ (E盤為項(xiàng)目所在的磁盤)

圖片.png
在初始化類中配置不同文件保存的不同的文件夾
@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("圖片格式不規(guī)范!");
}
if (file.getSize() > 1 * 1024 * 200) {
return ResultFactory.buildFailResult("小于200KB的照片才允許上傳!");
}
} else {
return ResultFactory.buildFailResult("圖片格式不規(guī)范!");
}
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 ,但是實(shí)際圖片存放的路徑為E:/home/gscq073240j/myfile/temp_qbs5/img/uuid的值.jpg.
項(xiàng)目的頁面樣式為

圖片.png
圖片此時的回顯

圖片.png
訪問的路徑如上圖。
所以需要配置靜態(tài)資源訪問路徑:
@Configuration
public class SpringWebMvcConfigurer extends WebMvcConfigurationSupport {
/**
* 配置靜態(tài)訪問資源
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
/* String p = new File(path).getAbsolutePath() + File.separator;//取得在服務(wù)器中的絕對路徑
System.out.println("Mapping /upload/** from " + p);
registry.addResourceHandler("/upload/**") // 外部訪問地址
.addResourceLocations("file:" + p)// springboot需要增加file協(xié)議前綴
.setCacheControl(CacheControl.maxAge(30, TimeUnit.MINUTES));// 設(shè)置瀏覽器緩存30分鐘*/
// 覆蓋默認(rèn)配置,自定義
registry.addResourceHandler("/upload/**").addResourceLocations("file:"+ FileUploadPathConfig.UPLOAD_PATH);
registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/", "classpath:/static/static/");
super.addResourceHandlers(registry);
}
}
此時圖片就能回顯了。
添加用戶,保存包數(shù)據(jù)庫
控制層:
/**
* 新增專家用戶
* @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類轉(zhuǎn)實(shí)體類
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 方法
將存入數(shù)據(jù)庫的值/upload/img/uuid的值.jpg改為/upload/img/身份證號.jpg,并將文件夾中實(shí)際的圖片的文件名renameto(文件移動)為身份證號.jpg

圖片.png
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;
}
}