SpringBoot上传图片操作

本文介绍了一个Java文件上传工具类的实现,包括文件上传方法、配置真实路径与虚拟路径映射,以及如何处理上传文件的存储和返回虚拟路径。

    首先有个上传文件的工具类

/**
 * 文件上传
 * @param file
 * @param filePath
 * @param fileName
 * @throws Exception
 */
public static void uploadFile(byte[] file, String filePath, String fileName) throws Exception {
    File targetFile = new File(filePath);
    if(!targetFile.exists()){
        targetFile.mkdirs();
    }
    FileOutputStream out = new FileOutputStream(filePath+File.separator+fileName);
    out.write(file);
    out.flush();
    out.close();
}

 

2. 配置真实路径与虚拟路径的映射关系

public class TestApplication extends WebMvcConfigurerAdapter {


    public static void main(String[] args) {
        SpringApplication.run(TestApplication.class, args);
    }


    @Value("${upload.filePath}")
    private String filePath;


    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry){
        registry.addResourceHandler("/");
        registry.addResourceHandler("/images/**").addResourceLocations("file:"+filePath);
        super.addResourceHandlers(registry);
    }

}

 3. 上传的主要方法实现

@PostMapping("/test/common/uploadFile")
    public String uploadFile(
                    @RequestParam("file") MultipartFile file, HttpServletRequest request) {

        try {
               //定义相对路径
            String relativePath = File.separator+DateUtil.getToday()+File.separator;
            String path = filePath + relativePath;
            String fileName = file.getOriginalFilename();
            String uuid = UUID.randomUUID().toString().replaceAll("-","");
            String suffix = fileName.substring(fileName.lastIndexOf("."));


               //随机生成新的文件名,防止文件名冲突或者中文乱码问题
            String newFileName = uuid+suffix;

               //调用上传方法将文件上传到物理路径下
            FileUtil.uploadFile(file.getBytes(),path,newFileName);


            //可选:将图片路径存储起来为了定期清理图片(可以存储到非关系型数据库中,如mongodb)
            PicturePathDTO dto = new PicturePathDTO();
            dto.setPath(images+relativePath+newFileName);
            dto.setCreateTime(new Date());
            picturePathDao.save(dto);


            //返回虚拟路径
            return (images+relativePath+newFileName);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

转载于:https://my.oschina.net/u/2329222/blog/3002404

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值