当我们在做项目的时候,文件上传是必须做的,但是小项目搭建或者购买文件服务器成本比较高,也对维护增加了隐形的成本,有同学肯定想过上传到项目文件中,但是又不便于管理,文件和代码放一起,比某凡还难;那么有什么解决办法吗? 答案是肯定的;
当然了,在资源充足情况下,建议还是购买oss文件存储或者自己搭建文件服务器,话不多说直接上代码:
file:
resourceLocation: /fileService
我们先添加一个相对路径,我们要用tomcat映射到这个位置;
/**
* @Auther: MR.rp
* @Date: 2021/7/22 22:30
* @Description:
*/
@Configuration
@Slf4j
public class WebMvcConfig implements WebMvcConfigurer {
//从配置文件中加载静态资源相对路径
@Value(value = "${file.resourceLocation}")
private String resourceLocation;
// 实现静态资源的映射
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
File parentFile = new File(System.getProperty("user.dir")); //放在工作目录
String fileServicePath = resourceLocation;
if(parentFile.exists()) {
File file=new File(parentFile.getPath()+resourceLocation);
if(!file.exists()){//如果文件夹不存在
file.mkdir();//创建文件夹
log.info("创建文件服务文件夹:"+fileServicePath +"成功");
}
fileServicePath = file.getAbsolutePath()+File.separator;
}
registry.addResourceHandler("/**")
.addResourceLocations("classpath:/META-INF/resources/") // 映射swagger2
.addResourceLocations("file:"+fileServicePath) // 映射本地静态资源
.addResourceLocations("classpath:/resources/")
.addResourceLocations("classpath:/static/");
}
}
讲下: user.dir 为工作目录,我们可以在这个文件下创建文件服务文件夹也就是我们创建的/fileService文件夹,如果打jar包部署,这个文件夹就创建在jar包平行的位置,当然你也可以直接在配置文件中写死绝对路径,我们接着写下文件上传的服务来测试一下:
/**
* @Auther: MR.rp
* @Date: 2021/11/3 19:08
* @Description:
*/
@Service
public class FileServiceImpl implements FileService {
private static Logger log = Logger.getLogger(FileServiceImpl.class);
@Value(value = "${file.resourceLocation}")
private String resourceLocation;
public ServerResponseVO upload(@RequestPart(value = "file") MultipartFile file){
String fileHome = new File(System.getProperty("user.dir")+resourceLocation).getAbsolutePath();
if (file != null) {
HashMap<String,String> urlMap = null;
try {
// 获得文件上传的文件名称
String fileName = file.getOriginalFilename();
if (fileName == null || fileName.length()<1) {
return ServerResponseVO.error("文件不能为空");
}
// 文件重命名
String fileNameArr[] = fileName.split("\\.");
// 获取文件的后缀名
String suffix = fileNameArr[fileNameArr.length - 1];
String pathBody = "";
if (!suffix.equalsIgnoreCase("png") &&
!suffix.equalsIgnoreCase("jpg") &&
!suffix.equalsIgnoreCase("jpeg")) {
//pathBody = File.separator+"file"+ File.separator;
pathBody = File.separator+"file"+File.separator;
} else {
pathBody = File.separator+"images"+File.separator;
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
String str = sdf.format(new Date());
String newFileName = str + UUID.randomUUID().toString().replace("-", "")+"."+suffix;
String pathName = fileHome+pathBody+newFileName;
File newfile = new File(pathName);
if (!newfile.getParentFile().exists()) {
newfile.getParentFile().mkdirs();
}
file.transferTo(newfile);
String pathUrl = pathBody+newFileName;
urlMap = new HashMap<String,String>();
urlMap.put("pathUrl",pathUrl);
urlMap.put("fileName",newFileName);
log.info("==================== 文件上传成功 ==========================");
log.info(pathUrl);
} catch (IOException e) {
e.printStackTrace();
return ServerResponseVO.error(e.getMessage());
}
return ServerResponseVO.success("上传成功",urlMap);
}else{
return ServerResponseVO.error("文件不能为空");
}
}
}
再定义下接口:
/**
* @Auther: MR.rp
* @Date: 2021/11/3 19:21
* @Description:
*/
@Api(tags = "文件管理")
@RequestMapping("/admin")
@RestController
public class AdminFileController {
@Autowired
private FileService fileService;
@PostMapping("/upload")
@Transactional
@ApiOperation(value = "文件上传",notes = "文件上传")
public ServerResponseVO fileUpload(@RequestPart(value = "file") MultipartFile file){
return fileService.upload(file);
}
}
启动测试一下:
我们可以看到文件就放在项目的目录中,我们打jar包试试:
我们可以看到jar包平行位置创建了这个文件夹,上传文件也是没有问题的,我就不再测试了