SpringBoot中图片的上传与获取

上传图片:

@ApiOperation("上传图片")
@PostMapping("/uploadImage")
@ResponseBody
public ResultData uploadImage(@RequestParam MultipartFile multipartFile) {

    if (multipartFile.isEmpty()) {
        throw new BDException("请选择图片");
    }

    //检查格式
    String fileType = multipartFile.getContentType();
    logger.info("文件类型:" + fileType);
    boolean flag = false;
    for (String type : uploadImageTypes) {
        if (fileType.equals(type)) {
            flag = true;
            break;
        }
    }
    if (!flag) {
        throw new BDException("请选择 png、jpg、jpeg、gif、bmp 格式的图片");
    }

    //检查文件大小
    double imageSize = (double) multipartFile.getSize() / 1024 / 1024;
    NumberFormat nf = new DecimalFormat("0.00");
    logger.info("图片大小:" + Double.parseDouble(nf.format(imageSize)) + "M");
    if (imageSize > uploadImageSize) {
        throw new BDException("请上传" + uploadImageSize + "M以内图片");
    }

    String fileName = multipartFile.getOriginalFilename();//文件名
    String suffixName = fileName.substring(fileName.lastIndexOf("."));//后缀名

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM");
    String format = simpleDateFormat.format(new Date());

    String path = "D:/slkjImage/news" + "/" + format; //文件存储位置
    fileName = UUID.randomUUID() + suffixName;//图片名
    String imageUrl = path + "/" + fileName;//图片的url
    logger.info("图片URL:" + imageUrl);
    File dest = new File(imageUrl);
    if (!dest.getParentFile().exists()) {
        dest.getParentFile().mkdirs();
    }
    try {
        multipartFile.transferTo(dest);
        return ResultDataUtils.success("上传成功", imageUrl);
    } catch (IOException e) {
    }
    return ResultDataUtils.fail("上传失败");
}

获取图片

@ApiOperation("获取图片")
@GetMapping("/getImage")
@ResponseBody
public void getImage(@RequestParam String imageUrl, HttpServletResponse response) {
    if (imageUrl != null) {
        logger.info("请求的图片URL:" + imageUrl);
        FileInputStream in = null;
        OutputStream out = null;
        try {
            File file = new File(imageUrl);
            if (!file.exists()) {
                throw new BDException("图片不存在");
            }
            in = new FileInputStream(imageUrl);
            int i = in.available();
            byte[] buffer = new byte[i];
            in.read(buffer);
            //设置输出流内容格式为图片格式
            response.setContentType("image/jpeg");
            //response的响应的编码方式为utf-8
            response.setCharacterEncoding("utf-8");
            out = response.getOutputStream();
            out.write(buffer);
        } catch (Exception e) {
            throw new BDException("网络错误");
        } finally {
            try {
                in.close();
                out.close();
            } catch (IOException e) {
                throw new BDException("网络错误");
            }
        }
    }
}
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在 Spring Boot 获取图片的地址,可以借助 Spring MVC 提供的 MultipartFile 类。MultipartFile 类是 Spring MVC 上文件的核心类,可以用来接收客户端上的文件。具体步骤如下: 1. 在 Controller 定义上图片的接口,使用 @PostMapping 注解标注该接口,并使用 @RequestParam 注解指定上图片的参数名。 示例代码: ```java @PostMapping("/upload") public String upload(@RequestParam("file") MultipartFile file) { // 处理上图片的逻辑 } ``` 2. 在 upload 方法,使用 MultipartFile 的 transferTo 方法将上图片保存到指定的位置,并返回图片的地址。 示例代码: ```java @PostMapping("/upload") public String upload(@RequestParam("file") MultipartFile file) throws IOException { // 获取图片的文件名 String filename = file.getOriginalFilename(); // 获取图片的后缀名 String suffix = filename.substring(filename.lastIndexOf(".")); // 生成保存图片的文件名 String saveFilename = UUID.randomUUID().toString() + suffix; // 保存上图片 file.transferTo(new File("保存图片的路径" + saveFilename)); // 返回图片的地址 return "http://图片服务器的域名/" + saveFilename; } ``` 在上面的代码,我们使用了 UUID 来生成保存图片的文件名,确保文件名的唯一性。在实际开发,你需要将 "保存图片的路径" 替换为你要保存图片的路径,将 "http://图片服务器的域名/" 替换为你的图片服务器的域名。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值