Java图片文件上传及回显

1. 图片上传及回显工具类

import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;

public class LoadUtil {

    //上传图片
    public static String uploadImg(MultipartFile multipartFile, String basePath) {
        // 获取绝对路径
        File f = new File(basePath);
        // 如果不存在,直接创建
        if (!f.exists()) {
            f.mkdirs();
        }
        // 获取原图片名称
        String originalFilename = multipartFile.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        // 使用UUID生成文件名
        String filename = UUID.randomUUID() + suffix;
        // 拼接的图片路径
        String filepath = basePath + filename;
        File file = new File(filepath);
        // 上传图片
        try {
            multipartFile.transferTo(file);
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return filepath;
    }

    // 回显图片
    public static void showImg(String imgUrl, HttpServletResponse response) {
        // 获取图片的当前路径 放入读
        FileInputStream fis = null;
        // 用response 获取一个写对象的流
        ServletOutputStream os = null;
        try {
            fis = new FileInputStream(imgUrl);
            os = response.getOutputStream();
            // 提高读写的速度
            byte[] b = new byte[1024];
            // 边读边写
            while (fis.read(b) != -1) {
                os.write(b);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (os != null) {
                    os.close();
                }
                if (fis != null) {
                    fis.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    // 下载
    public static void downLoad(String filePath, HttpServletRequest request, HttpServletResponse response) {
        //设置文件的MiMe类型
        response.setContentType(request.getSession().getServletContext().getMimeType(filePath));
        //设置content-disposition
        response.setHeader("Content-Disposition", "attachment;filename=" + filePath);
        //读取目标文件,通过response将目标文件写到客户
        try {
            // 读取文件
            InputStream in = new FileInputStream(filePath);
            OutputStream out = response.getOutputStream();
            //写文件
            byte[] b = new byte[1024];
            while (in.read(b) != -1) {
                out.write(b);
            }
            in.close();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

 2. 调用工具类

配置存储路径

# 文件存储路径
file:
  mac:
    path: ~/file/
    avatar: ~/avatar/
  linux:
    path: /home/business/file
    avatar: /home/business/avatar
  windows:
    path: C:/business/file
    avatar: C:/business/avatar
  # 文件大小 /M
  maxSize: 100
  avatarMaxSize: 5

 调用

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/img")
public class ImgTest {

    @Value("${file.windows.path}")
    private String basePath;

    /**
     * 上传图片
     */
    @PostMapping("uploadImg")
    public ResponseEntity<String> uploadImg(MultipartFile file) {
        String imgUrl = LoadUtil.uploadImg(file, basePath);
        return ResponseEntity.ok(imgUrl);
    }

    /**
     * 回显图片
     */
    @GetMapping("showImg")
    public void showImg(HttpServletResponse response, @RequestParam("imgUrl") String imgUrl) {
        LoadUtil.showImg(imgUrl, response);
    }
}

  • 1
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
以下是一个基于Spring Boot的图片上传回显的代码实现示例,其中使用了Thymeleaf模板引擎: 1. 配置文件中添加文件上传配置: ```yaml spring: servlet: multipart: max-file-size: 10MB # 文件大小限制 max-request-size: 10MB # 请求大小限制 file-size-threshold: 2KB # 临时文件大小限制 ``` 2. 控制器中添加上传及回显的方法: ```java @Controller public class ImageController { // 上传图片页面 @GetMapping("/upload") public String uploadPage(Model model) { model.addAttribute("image", new Image()); return "upload"; } // 上传图片回显 @PostMapping("/upload") public String uploadImage(@ModelAttribute("image") Image image, BindingResult result) throws IOException { if (result.hasErrors()) { return "upload"; } // 保存图片到本地文件系统 byte[] bytes = image.getFile().getBytes(); Path path = Paths.get("images/" + image.getFile().getOriginalFilename()); Files.write(path, bytes); // 设置图片URL image.setUrl("/images/" + image.getFile().getOriginalFilename()); return "redirect:/upload"; } } ``` 3. 在Thymeleaf模板中添加上传表单及回显图片: ```html <!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Image Upload</title> </head> <body> <h1>Image Upload</h1> <!-- 上传表单 --> <form action="#" th:action="@{/upload}" th:object="${image}" method="post" enctype="multipart/form-data"> <div> <label for="file">Choose an image:</label> <input type="file" id="file" name="file" accept="image/*" required="required" th:field="*{file}" /> </div> <div> <button type="submit">Upload</button> </div> </form> <!-- 回显图片 --> <div th:if="${image.url != null}"> <img th:src="@{${image.url}}" alt="Uploaded image" /> </div> </body> </html> ``` 其中,Image类用于封装上传的文件和回显图片URL: ```java public class Image { private MultipartFile file; private String url; // getters and setters } ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值