前言
本文主要做基本的图片下载示例
实现
通过字节流返回
这种方案是最基本的方案,包括oss图片链接和所有直接通过url请求的图片都是这种方式实现的。该方案的图片在浏览器可以直接打开
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
| package cn.idea360.demo.modules.login;
import cn.idea360.demo.common.utils.QrcodeUtil; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.FileInputStream; import java.io.OutputStream; import java.util.Base64;
@RestController @RequestMapping("/qr") public class QrController {
@RequestMapping(value = "/img", produces = MediaType.IMAGE_JPEG_VALUE) public void getImageByBytes(HttpServletResponse response) throws Exception{ File file = new File("C:\\Users\\Administrator\\Desktop\\1.jpg"); FileInputStream inputStream = new FileInputStream(file); byte[] bytes = new byte[inputStream.available()]; inputStream.read(bytes, 0, inputStream.available());
response.setContentType("image/jpeg"); response.setCharacterEncoding("UTF-8"); response.setHeader("Accept-Ranges", "bytes"); OutputStream outputSream = response.getOutputStream(); outputSream.write(bytes); outputSream.flush(); } }
|
通过base64返回
该方案返回类型是base64编码的字符串, 放在h5的img标签中渲染。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| package cn.idea360.demo.modules.login;
import cn.idea360.demo.common.utils.QrcodeUtil; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.FileInputStream; import java.io.OutputStream; import java.util.Base64;
@RestController @RequestMapping("/qr") public class QrController {
@RequestMapping(value = "/base64img") public String getImageByBase64() throws Exception { File file = new File("C:\\Users\\Administrator\\Desktop\\1.jpg"); FileInputStream inputStream = new FileInputStream(file); byte[] bytes = new byte[inputStream.available()]; inputStream.read(bytes, 0, inputStream.available()); return "data:image/jpg;base64," + Base64.getEncoder().encodeToString(bytes); } }
|
最后
本文到此结束,感谢阅读。如果您觉得不错,请关注公众号【当我遇上你】,您的支持是我写作的最大动力。