springboot下文件上传。

1.本地上传到E盘下的image目录

@Slf4j
@RestController
public class UploadController {
    @PostMapping("/upload")
    public Result upload(MultipartFile image) throws IOException {
        log.info("文件上传:{}",image);
        String originalFilename = image.getOriginalFilename();
        image.transferTo(new File("E:\\image\\"+originalFilename));
        return Result.success();
    }
}

2.本地上传并重命名图片名称

uuid可以生成唯一标签(有极小概率会重复)

@Slf4j
@RestController
public class UploadController {
    @PostMapping("/upload")
    public Result upload(MultipartFile image) throws IOException {
        log.info("文件上传:{}",image);
        String originalFilename = image.getOriginalFilename();
        int index=originalFilename.lastIndexOf(".");
        String extname = originalFilename.substring(index);
        String newFileName= UUID.randomUUID().toString()+extname;
        log.info("新的文件名:{}",newFileName);
        image.transferTo(new File("E:\\image\\"+newFileName));
        return Result.success();
    }
}

3.本地上传并重命名图片名称并返回文件地址

@Slf4j
@RestController
public class UploadController {
    @PostMapping("/upload")
    public Result upload(MultipartFile image) throws IOException {
        log.info("文件上传:{}",image.getOriginalFilename());
        String originalFilename = image.getOriginalFilename();
        int index=originalFilename.lastIndexOf(".");
        String extname = originalFilename.substring(index);
        String newFileName= UUID.randomUUID().toString()+extname;
        log.info("新的文件名:{}",newFileName);
        image.transferTo(new File("E:\\image\\"+newFileName));
        String url="E:\\image\\"+newFileName;
        log.info("文件地址为{}",url);
        return Result.success(url);
    }
}

 

posted @ 2023-12-13 17:09  Triassic  阅读(30)  评论(0编辑  收藏  举报