文件上传(upload)
程序员文章站
2022-06-13 15:57:40
...
一、文件上传
public UploadResult upload(MultipartFile file) {
Assert.notNull(file, "Multipart file must not be null");
// Get current time 获取当前时间
Calendar current = Calendar.getInstance(optionService.getLocale());
// Get month and day of month 获取当前年和月
int year = current.get(Calendar.YEAR);
int month = current.get(Calendar.MONTH) + 1;
String monthString = month < 10 ? "0" + month : String.valueOf(month);
// Build directory 构建上传文件存储目录
String subDir = UPLOAD_SUB_DIR + year + FILE_SEPARATOR + monthString + FILE_SEPARATOR;
//获取上传文件名
String originalBasename = FilenameUtils.getBasename(Objects.requireNonNull(file.getOriginalFilename()));
// Get basename 构建文件名
String basename = originalBasename + '-' + HaloUtils.randomUUIDWithoutDash();
// Get extension 构建文件类型
String extension = FilenameUtils.getExtension(file.getOriginalFilename());
log.debug("Base name: [{}], extension: [{}] of original filename: [{}]", basename, extension, file.getOriginalFilename());
// Build sub file path 构建子文件路径
String subFilePath = subDir + basename + '.' + extension;
// Get upload path 构建上传文件存储目录路径
Path uploadPath = Paths.get(workDir, subFilePath);
log.info("Uploading file: [{}]to directory: [{}]", file.getOriginalFilename(), uploadPath.toString());
try {
// TODO Synchronize here
// Create directory 创建目录,创建文件
Files.createDirectories(uploadPath.getParent());
Files.createFile(uploadPath);
// Upload this file 上传文件
file.transferTo(uploadPath);
// Build upload result 构建上传结果
UploadResult uploadResult = new UploadResult();
uploadResult.setFilename(originalBasename);
uploadResult.setFilePath(subFilePath);
uploadResult.setKey(subFilePath);
uploadResult.setSuffix(extension);
uploadResult.setMediaType(MediaType.valueOf(Objects.requireNonNull(file.getContentType())));
uploadResult.setSize(file.getSize());
// TODO refactor this: if image is svg ext. extension
boolean isSvg = "svg".equals(extension);
// Check file type 检查文件类型
if (FileHandler.isImageType(uploadResult.getMediaType()) && !isSvg) {
lock.lock();
try (InputStream uploadFileInputStream = new FileInputStream(uploadPath.toFile())) {
// Upload a thumbnail 上传压缩图
String thumbnailBasename = basename + THUMBNAIL_SUFFIX;
String thumbnailSubFilePath = subDir + thumbnailBasename + '.' + extension;
Path thumbnailPath = Paths.get(workDir + thumbnailSubFilePath);
// Read as image 解读为图像
BufferedImage originalImage = ImageUtils.getImageFromFile(uploadFileInputStream, extension);
// Set width and height
uploadResult.setWidth(originalImage.getWidth());
uploadResult.setHeight(originalImage.getHeight());
// Generate thumbnail 生成缩略图
boolean result = generateThumbnail(originalImage, thumbnailPath, extension);
if (result) {
// Set thumb path 设置缩略图路径
uploadResult.setThumbPath(thumbnailSubFilePath);
} else {
// If generate error
uploadResult.setThumbPath(subFilePath);
}
} finally {
lock.unlock();
}
} else {
uploadResult.setThumbPath(subFilePath);
}
log.info("Uploaded file: [{}] to directory: [{}] successfully", file.getOriginalFilename(), uploadPath.toString());
return uploadResult;
} catch (IOException e) {
throw new FileOperationException("上传附件失败").setErrorData(uploadPath);
}
}
//获取文件名 例如: houtai2.jpg --> houtai2
@NonNull
public static String getBasename(@NonNull String filename) {
Assert.hasText(filename, "Filename must not be blank");
// Find the last slash
int separatorLastIndex = StringUtils.lastIndexOf(filename, File.separatorChar);
if (separatorLastIndex == filename.length() - 1) {
return StringUtils.EMPTY;
}
if (separatorLastIndex >= 0 && separatorLastIndex < filename.length() - 1) {
filename = filename.substring(separatorLastIndex + 1);
}
// Find last dot
int dotLastIndex = StringUtils.lastIndexOf(filename, '.');
if (dotLastIndex < 0) {
return filename;
}
return filename.substring(0, dotLastIndex);
}
@NonNull // 构建文件的类型 例如: houtai2.jpg -- > jpg
public static String getExtension(@NonNull String filename) {
Assert.hasText(filename, "Filename must not be blank");
// Find the last slash
int separatorLastIndex = StringUtils.lastIndexOf(filename, File.separatorChar);
if (separatorLastIndex == filename.length() - 1) {
return StringUtils.EMPTY;
}
if (separatorLastIndex >= 0 && separatorLastIndex < filename.length() - 1) {
filename = filename.substring(separatorLastIndex + 1);
}
// Find last dot
int dotLastIndex = StringUtils.lastIndexOf(filename, '.');
if (dotLastIndex < 0) {
return StringUtils.EMPTY;
}
return filename.substring(dotLastIndex + 1);
}
//返回图像数据缓存区
public static BufferedImage getImageFromFile(InputStream is, String extension) throws IOException {
log.debug("Current File type is : [{}]", extension);
if (EXTENSION_ICO.equals(extension)) {
return ICODecoder.read(is).get(0);
} else {
return ImageIO.read(is);
}
}
上一篇: CPU中TDP技术是什么及其功耗介绍
下一篇: 中国是苹果发展的机会