前端界面根据条件动态显示图片

今天碰到了需要根据特定数据动态显示有关图片的问题(从数据库中查询处图片名称)

1、显示项目目录下的图片
html代码:

  <div id = "content" style = "background-color:white;width:900px;height:650px;margin-left:150px;margin-top:70px">    
      <img id = "fileImg" alt='' style = 'height:100%;width:100%'>
 </div>

图片所在项目目录:
在这里插入图片描述

js代码:

//点击查看图片按钮
    $("#queryFile").click(function(){
    	$("#fileImg").show()
    	console.log(fileObj)
    	var certificate = fileObj.certificate
    	console.log(certificate)
    	// 为img标签设置src属性值; '/static/img/' 为图片在项目目录下保存的路径,imgName是从数据库中查询出的图片名称,如 01.PNG  ; 
    	$("#fileImg").attr('src','/static/context/images/'+imgName)
     	
    })

2、显示服务器本地目录下的图片
因为服务器都有保护机制,不能直接从web端读取服务器本地文件,所以需要通过IO流将图片写出到前端界面显示
html代码:

  <div id = "content" style = "background-color:white;width:900px;height:650px;margin-left:150px;margin-top:70px">    
      <img id = "fileImg" alt='' style = 'height:100%;width:100%'>
 </div>

js代码:

//点击某个按钮显示图片
   $("#queryCertificate").click(function(){
    	$("#fileImg").show()
    	console.log(fileObj)
    	var certificate = fileObj.certificate
    	console.log(certificate)
    	//<img标签的src路径设置为后端的接口路径,并通过get请求向后端接口传递参数(比如文件类型和用户对应id)>
     	$("#fileImg").attr('src','/hzsh/eomc-zhch/ryzzwh/queryFile?type=img&id='+id)	
    })

后端代码:

	/**
	 * 查询用户对应图片,写出出到前端页面
	 * 
	 * @param id
	 */

	@ResponseBody
	@RequestMapping("/queryFile")
	public void queryFileByEmployeeId(HttpServletRequest request, HttpServletResponse response) {
	
		String type = request.getParameter("type");
		String id= request.getParameter("id");
		User user = new User();
	    String fileName = user.getFileName();
		// 获取对应的图片;'D:/tmp/attach/'是图片在服务器的目录
		try {
			File file = new File("D:/tmp/attach/" + fileName );
			FileInputStream fis = new FileInputStream(file);
			OutputStream out = response.getOutputStream();
			long size = file.length();
			byte[] temp = new byte[(int) size];
			fis.read(temp, 0, (int) size);
			fis.close();
			byte[] data = temp;

			if (type == "img") {
				response.setContentType("image/PNG");
			} else if (type == "doc") {
				response.setContentType("application/msword");
			}

			// response.setContentType("application/msword");
			// data = Base64.encodeBase64(data);
			out.write(data);
			out.flush();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

这里只是我在项目中遇到的两种动态显示图片的方式,只是列出了两种情况下如何显示图片,至于如何上传到项目目录或服务器本地目录,以后有空再做总结

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值