SpringBoot实现的图片预览地址

懒驴 2021年12月21日 520次浏览

有时候项目会遇到需要后端直接提供一个请求地址,浏览器打开直接就是显示图片,而非下载,SpringBoot项目中的具体实现代码如下:


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

/***
 * 图片预览地址
 * imgStrId 图片ID的参数,可以不需要,安装自己的业务逻辑
 **/
@RestController
@RequestMapping("/image")
public class ImageController {
	@RequestMapping(value = "/getview-image/{imgStrId}", method = {RequestMethod.GET, RequestMethod.POST}, produces = MediaType.IMAGE_JPEG_VALUE)
	public void getPreviewImageMethod(@PathVariable String imgStrId, HttpServletRequest request, HttpServletResponse response) throws Exception{
    		InputStream inputStream = new FileInputStream(new File("自己的图片地址路径"));
            InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
            response.setContentType(MediaType.IMAGE_PNG_VALUE);

            ServletOutputStream outputStream = null;

            try {
                response.setContentType("image/png");
                outputStream = response.getOutputStream();
                int len = 0;
                byte[] buffer = new byte[4096];
                while ((len = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, len);
                }
                outputStream.flush();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                outputStream.close();
                inputStream.close();
            }
	
	}
}