说两种方式,直接上代码:
1.前提图片已经存储在服务器上,携带图片地址过去通过输入输出流进行图片下载查看
前端:
<img v-else :src="'/chat/download?name='+message.url"/>
后端:
@GetMapping("/download")public void download(String name, HttpServletResponse response) {try {//输入流,通过输入流读取文件内容FileInputStream fileInputStream = new FileInputStream(new File(basePath + name));//输出流,通过输出流将文件写回浏览器ServletOutputStream outputStream = response.getOutputStream();response.setContentType("image/jpeg");int len = 0;byte[] bytes = new byte[1024];while ((len = fileInputStream.read(bytes)) != -1) {outputStream.write(bytes, 0, len);outputStream.flush();}//关闭资源outputStream.close();fileInputStream.close();} catch (Exception e) {e.printStackTrace();}}
2.通过1的方式不能直接获取http/https路径进行访问,接下来看第二种方式
2.1—先写静态资源映射
@Configuration
@Slf4j
//public class WebMvcConfiguration extends WebMvcConfigurationSupport {
public class WebMvcConfiguration implements WebMvcConfigurer {@Overridepublic void addResourceHandlers(ResourceHandlerRegistry registry) {log.info("开启静态资源映射");// 静态资源映射// 这个/www/server/img2 这个是我服务器上存储图片的路径registry.addResourceHandler("/img2/**").addResourceLocations("file:/www/server/img2/"); }}
这样映射后就能通过http/https进行访问,可以:src进行动态绑定,然后拼装路径就可以直接访问
<image src="https://qianyekeji.cn/img2/EDJW5xpf91GXc6d354d47eeae6137132e16352ab3e23.jpg" mode="aspectFill" v-else @click="preView(item.image)"></image>