图片上传下载

springBoot上传限制默认为1MB
可以在yml文件中配置
spring:
servlet:
multipart:
max-file-size: 10MB
max-request-size: 10MB

//tomcat 映射地址
private String fileUploadUrlStr = “http://127.0.0.1:46585/upload”;

@ApiOperation("图片上传")
@PostMapping("/uPicture")
public CommonResult<String> uploadPicture(@RequestParam("file") MultipartFile file) {
	//上传的文件名称
    String fileName = file.getOriginalFilename();
    System.out.println(fileName);
    long size = file.getSize();

    //图片保存地址
    String filePath = System.getProperty("user.dir") + "/fileImg/" + System.currentTimeMillis() + ".jpg";

    log.info("图片路径:" + filePath);
    //映射地址+图片名称
    String pictureUrl = fileUploadUrlStr + filePath.substring(filePath.lastIndexOf("/"));

    File dest = new File(filePath);
    if (!dest.getParentFile().exists()) {
        dest.getParentFile().mkdirs();
    }
    try {
        file.transferTo(dest);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    return CommonResult.success(pictureUrl);
}


@GetMapping("/download")
@ApiOperation("下载图片")
public void download(@RequestParam("path") String path, HttpServletResponse response) {
    try {
        // 1、定义输入流,通过输入流读取文件内容
        String filePath = System.getProperty("user.dir") + "/fileImg";
        String name = path.substring(path.lastIndexOf("/"));
        FileInputStream fileInputStream = new FileInputStream(filePath + name);

        // 2、通过response对象,获取到输出流
        ServletOutputStream outputStream = response.getOutputStream();

        // 3、通过response对象设置响应数据格式(image/jpeg)
        response.setContentType("image/jpeg");

        int len = 0;
        byte[] bytes = new byte[1024];
        while ((len = fileInputStream.read(bytes)) != -1) {
            // 4、通过输入流读取文件数据,然后通过上述的输出流写回浏览器
            outputStream.write(bytes, 0, len);
            // 刷新
            outputStream.flush();
        }
        // 5、关闭资源
        outputStream.close();
        fileInputStream.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值