mysql 使用mybatis保存图片

1、创建springboot项目

2、引入依赖



	4.0.0
	
		org.springframework.boot
		spring-boot-starter-parent
		2.1.9.RELEASE
		 
	
	com.llg
	mybatis
	0.0.1-SNAPSHOT
	mybatis
	Demo project for Spring Boot

	
		1.8
	

	
		
			org.springframework.boot
			spring-boot-starter-jdbc
		
		
			org.springframework.boot
			spring-boot-starter-web
		
		
			org.mybatis.spring.boot
			mybatis-spring-boot-starter
			1.3.2
		

		
			mysql
			mysql-connector-java
			runtime
		
		
			org.springframework.boot
			spring-boot-starter-test
			test
		

	

	
		
			
				org.springframework.boot
				spring-boot-maven-plugin
			
		
	


3、实体类

package com.llg.mybatis.entity;

import lombok.Data;

@Data
public class Users {
    private Integer id;
    private String username;
    private String password;
    private byte[] pic;
}

4、前端页面




    
    Title


    

5、上传方法

@PostMapping("/upload")
public String savePic(@RequestParam("file") MultipartFile file){
	if (file.isEmpty()) {
		return "上传失败,请选择文件";
	}
	try {
		InputStream is = file.getInputStream();
		Users u = new Users();
		u.setUsername("哈哈");
		u.setUsername("123456");
		byte[] pic = new byte[(int)file.getSize()];
		is.read(pic);
		u.setPic(pic);
		userService.addUser(u);
		return "上传成功";
	} catch (IOException e) {
		e.printStackTrace();
	}
	return "success";
}

6、mapper sql语句


    insert into users (username, password, pic) values (#{username}, #{password}, #{pic})

7、启动程序-打开页面-上传图片

mysql 使用mybatis保存图片_第1张图片

成功

mysql 使用mybatis保存图片_第2张图片

8、前端获取数据库的图片并展示

后端代码

@GetMapping(value="/getPhoto")
public void getPhotoById(final HttpServletResponse response) throws IOException {
	Users users = userService.getLastUser();
	byte[] data = users.getPic();
	response.setContentType("image/jpeg");
	response.setCharacterEncoding("UTF-8");
	OutputStream outputSream = response.getOutputStream();
	InputStream in = new ByteArrayInputStream(data);
	int len = 0;
	byte[] buf = new byte[1024];
	while ((len = in.read(buf, 0, 1024)) != -1) {
		outputSream.write(buf, 0, len);
	}
	outputSream.close();
}

sql语句 

结果

mysql 使用mybatis保存图片_第3张图片

 

你可能感兴趣的:(java,mybatis,mybatis,文件上传,图片上传)