Spring boot 文件上传映射到服务器自定义目录(适用于小型项目)

当我们在做项目的时候,文件上传是必须做的,但是小项目搭建或者购买文件服务器成本比较高,也对维护增加了隐形的成本,有同学肯定想过上传到项目文件中,但是又不便于管理,文件和代码放一起,比某凡还难;那么有什么解决办法吗? 答案是肯定的;

当然了,在资源充足情况下,建议还是购买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包平行位置创建了这个文件夹,上传文件也是没有问题的,我就不再测试了

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值