import com.google.common.io.Files;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
/**
* @Auther: zyx.
* @Date: 2018/12/17 8:55
*/
@Slf4j
public class UploadFileUtils {
/**
* 上传单个文件,文件命名以
* 20181215T180946598
* 加后缀为列
* 返回文件路径
*
* @param: [file, uploadFilePath]
* @return: java.lang.String
* @date: 2018/12/17 9:14
*/
public static String upload(MultipartFile file, String uploadFilePath) {
if (null == file) {
return null;
}
String originalFileName = file.getOriginalFilename();
String fileExtension = Files.getFileExtension(originalFileName);
// create upload directory if not exist
createUploadDirIfNotExist(uploadFilePath);
String newFileAbsolutePath = generateFileAbsolutePath(uploadFilePath, fileExtension);
try {
file.transferTo(new File(newFileAbsolutePath));
} catch (IOException e) {
log.error("upload file error ", e);
return null;
}
return newFileAbsolutePath;
}
/**
* create upload directory if not exist.
*
* @param uploadFilePath upload directory
*/
private static void createUploadDirIfNotExist(String uploadFilePath) {
File uploadDir = new File(uploadFilePath);
if (!uploadDir.exists()) {
uploadDir.mkdirs();
}
}
/**
* absolute file root path + current time("yyyyMMdd'T'HHmmssSSS")
*
* @see DateUtils#T_PATTERN
*/
public static String generateFileAbsolutePath(String uploadDir, String fileExtension) {
// current time + "_" + generateId
String newFileName = DateUtils.formatT();
newFileName = uploadDir.concat(newFileName).concat(".").concat(fileExtension);
return newFileName;
}
}