springboot 如何上传图片文件到服务器的指定目录

  • 先在application.properties动态配置图片文件保存的位置
upload.filePath=/root/straw-app/uploadFile/
  • 然后写一个文件上传路径的配置类,这样在项目的其它地方可以通过依赖注入该类,并使用该配置
@Component
@ConfigurationProperties(prefix = "upload")
@Data
public class UploadFileConfig {
    private  String filePath;
}
  • 然后再写了一个WebMvcConfigurer的实现类,指定静态资源的映射。下面的意思是当我们访问/uploadFile/**的请求时,系统会把该请求映射到指定的文件目录。比如访问http://localhost:8080/uploadFile/**时,系统会到/root/straw-app/uploadFile/下去找相应的文件。
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Resource
    UploadFileConfig uploadFileConfig;
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
                            registry.addResourceHandler("/uploadFile/**").addResourceLocations("file:"+uploadFileConfig.getFilePath());
    }
}
  • controller的如下:
 @PostMapping("/uploadMultipleFile")
    @ApiOperation(value = "上传图片到图片服务器")
    @ResponseBody
    public StrawResult uploadImg(@RequestParam("file") MultipartFile[] files, HttpServletRequest request) throws IOException {
        return questionService.uploadImg(files, request);
    }
  • servie如下:
@Override
    public StrawResult uploadImg(MultipartFile[] files, HttpServletRequest request) {
        List images=new ArrayList<>();
        for(MultipartFile file:files){

            //获取绝对路径
            String realPath=fileConfig.getFilePath();
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy/MM/dd/");
            String format=sdf.format(new Date());
            //文件存放的目录
            File folder=new File(realPath+format);
            if(!folder.isDirectory()){
                folder.mkdirs();
            }
            String oldName=file.getOriginalFilename();
            //文件后缀
            String suffix=oldName.substring(oldName.lastIndexOf("."),oldName.length());
            //文件新名字
            String newName=UUID.randomUUID().toString()+suffix;
            try {
                File targetFile=new File(folder,newName);

                if(!targetFile.exists()){
                    targetFile.mkdirs();
                }else {
                    targetFile.delete();
                }
                file.transferTo(targetFile);
                String filePath=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+"/uploadFile/"+format+newName;
                images.add(filePath);
            }catch (IOException e){
                e.printStackTrace();
            }

        }
       return new StrawResult().success(images);

    }

 

你可能感兴趣的:(Springboot,spring,boot,java)