本例采用图片数据存储到数据库字段的方式
上传文件实体类
package com.test.model;
import java.io.Serializable;
import java.sql.Blob;
import java.sql.Date;
import javax.sql.rowset.serial.SerialBlob;
public class FileInfo implements Serializable{
private Integer id = null;
private String name = null;
private String contextType = null;
private Long length = null;
private Date dt = null;
private byte[] content = null;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getContextType() {
return contextType;
}
public void setContextType(String contextType) {
this.contextType = contextType;
}
public Long getLength() {
return length;
}
public void setLength(Long length) {
this.length = length;
}
public Date getDt() {
return dt;
}
public void setDt(Date dt) {
this.dt = dt;
}
public byte[] getContent() {
return content;
}
public void setContent(byte[] content) {
this.content = content;
}
}
商品分类关联上传文件
package com.test.model;
import java.util.ArrayList;
import java.util.List;
public class TypeInfo {
private Integer id = null;
private String label = null;
private Integer pid = null;
private Integer seqno = null;
private List<TypeInfo> children = new ArrayList<TypeInfo>();
private Integer imgid = null;
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getPid() {
return pid;
}
public void setPid(Integer pid) {
this.pid = pid;
}
public Integer getSeqno() {
return seqno;
}
public void setSeqno(Integer seqno) {
this.seqno = seqno;
}
public List<TypeInfo> getChildren() {
return children;
}
public void setChildren(List<TypeInfo> children) {
this.children = children;
}
public void addChildren(TypeInfo ti) {
this.children.add(ti);
}
public Integer getImgid() {
return imgid;
}
public void setImgid(Integer imgid) {
this.imgid = imgid;
}
}
SQL
drop table T_FILE;
create table T_FILE(id int auto_increment primary key,
name varchar(200),contexttype varchar(100),length bigint,dt date,content mediumblob);
Mybatis Mapper XML
<insert id="saveFile" parameterType="com.test.model.FileInfo" statementType="PREPARED"
useGeneratedKeys="true" keyColumn="id" keyProperty="id">
insert into T_FILE(name,contexttype,length,dt,content) values (#{name},#{contextType},
#{length},#{dt},#{content,jdbcType=BLOB})
</insert>
<select id="getFileById" resultType="com.test.model.FileInfo" statementType="PREPARED">
select * from T_FILE where id=#{id}
</select>
Mapper接口
package com.test.mapper;
import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import com.test.model.AddressInfo;
import com.test.model.FileInfo;
import com.test.model.StudentInfo;
import com.test.model.TypeInfo;
@Mapper
public interface AddressMapper {
public List<AddressInfo> getProvince();
public List<AddressInfo> getCity(@Param("code") String code);
public List<AddressInfo> getCounty(@Param("code") String code);
public void saveStudent(StudentInfo si);
public void updateStudent(StudentInfo si);
public List<StudentInfo> findStudent(@Param("name") String name,
@Param("age1") String age1,
@Param("age2") String age2);
public StudentInfo findStudentById(@Param("id") Integer id);
public void deleteStudent(@Param("id") Integer id);
public TypeInfo getRootType();
public List<TypeInfo> getTypeList(@Param("pid") Integer id);
public void updateType(TypeInfo ti);
public void saveType(TypeInfo ti);
public void saveFile(FileInfo fi);
public FileInfo getFileById(@Param("id") Integer id);
}
服务接口
package com.test.service;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import com.github.pagehelper.PageInfo;
import com.test.model.AddressInfo;
import com.test.model.FileInfo;
import com.test.model.StudentInfo;
import com.test.model.TypeInfo;
public interface IAddressService {
public List<AddressInfo> getProvince();
public List<AddressInfo> getCity(String code);
public List<AddressInfo> getCounty(String code);
public void updateStudent(StudentInfo si);
public void saveStudent(StudentInfo stud);
public PageInfo<StudentInfo> findStudent(Integer page,Integer rows,String name,String age1,String age2);
public StudentInfo findStudentById(Integer id);
public void deleteStudent(Integer id);
public TypeInfo getRootType();
public List<TypeInfo> getTypeList(Integer id);
public void updateType(TypeInfo ti);
public void saveType(TypeInfo ti);
public void saveFile(FileInfo fi);
public FileInfo getFileById(Integer id);
}
服务实现类
package com.test.service.impl;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.test.mapper.AddressMapper;
import com.test.model.AddressInfo;
import com.test.model.FileInfo;
import com.test.model.StudentInfo;
import com.test.model.TypeInfo;
import com.test.service.IAddressService;
@Service
public class AddressServiceImpl implements IAddressService{
@Autowired
private AddressMapper mapper;
@Override
public List<AddressInfo> getProvince() {
// TODO Auto-generated method stub
return mapper.getProvince();
}
@Override
public List<AddressInfo> getCity(String code) {
if(code != null)
{
String code2 = code.substring(0,2);
List<AddressInfo> citys = mapper.getCity(code2);
List<AddressInfo> resultCitys = new ArrayList<AddressInfo>();
for(AddressInfo city:citys)
{
if(!code.equals(city.getCode()))
resultCitys.add(city);
}
return resultCitys;
}
return null;
}
@Override
public List<AddressInfo> getCounty(String code) {
if(code != null)
{
String code2 = code.substring(0,4);
List<AddressInfo> countys = mapper.getCounty(code2);
List<AddressInfo> resultCountys = new ArrayList<AddressInfo>();
for(AddressInfo county:countys)
{
if(!code.equals(county.getCode()))
resultCountys.add(county);
}
return resultCountys;
}
return null;
}
@Override
public void saveStudent(StudentInfo stud) {
mapper.saveStudent(stud);
}
@Override
public PageInfo<StudentInfo> findStudent(Integer page,Integer rows,String name,
String age1,String age2) {
System.out.println("findStudent================page="+page+",rows="+rows+",name="+name);
if(page == null)
page = 1;
if(rows == null)
rows = 4;
PageHelper.startPage(page, rows);
List<StudentInfo> result = mapper.findStudent(name,age1,age2);
PageInfo<StudentInfo> pInfo = new PageInfo<StudentInfo>(result);
return pInfo;
}
@Override
public StudentInfo findStudentById(Integer id) {
// TODO Auto-generated method stub
return mapper.findStudentById(id);
}
@Override
public void updateStudent(StudentInfo si) {
mapper.updateStudent(si);
}
@Override
public void deleteStudent(Integer id) {
mapper.deleteStudent(id);
}
@Override
public TypeInfo getRootType() {
return mapper.getRootType();
}
@Override
public List<TypeInfo> getTypeList(Integer id) {
return mapper.getTypeList(id);
}
@Override
public void updateType(TypeInfo ti) {
mapper.updateType(ti);
}
@Override
public void saveType(TypeInfo ti) {
mapper.saveType(ti);
}
@Override
public void saveFile(FileInfo fi) {
mapper.saveFile(fi);
}
@Override
public FileInfo getFileById(Integer id) {
return mapper.getFileById(id);
}
}
Controller
package com.test.ctrl;
import static org.junit.Assert.assertNotNull;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.test.model.AddressInfo;
import com.test.model.FileInfo;
import com.test.model.StudentInfo;
import com.test.model.TypeInfo;
import com.test.service.IAddressService;
@Controller
@CacheConfig(cacheNames="student")
@CrossOrigin(origins = {"http://localhost:8080"})
public class StudCtrl {
@Autowired
private IAddressService addsrv;
@RequestMapping("/studlist")
public String studlist()
{
return "studlist";
}
@RequestMapping("/getprovice")
@ResponseBody
public List<AddressInfo> getprovice()
{
// List<Map> list = new ArrayList<Map>();
// Map m1 = new HashMap();
// m1.put("code","001");
// m1.put("name", "北京");
// list.add(m1);
// Map m2 = new HashMap();
// m2.put("code","002");
// m2.put("name", "上海");
// list.add(m2);
// return list;
return addsrv.getProvince();
}
@RequestMapping("/getcity")
@ResponseBody
public List<AddressInfo> getcity(String code)
{
return addsrv.getCity(code);
}
@RequestMapping("/getcounty")
@ResponseBody
public List<AddressInfo> getcounty(String code)
{
return addsrv.getCounty(code);
}
@RequestMapping("/savestudent")
@ResponseBody
@CacheEvict
public Boolean savestudent(HttpServletRequest req,@RequestBody StudentInfo si) throws Exception
{
/**
InputStream is = req.getInputStream();
byte[] content = FileCopyUtils.copyToByteArray(is);
System.out.println(new String(content));
JSONObject jsonObj = JSONObject.parseObject(new String(content));
StudentInfo si = (StudentInfo)JSONObject.toJavaObject(jsonObj,StudentInfo.class);
*/
System.out.println(si);
if(si.getId() != null)
addsrv.updateStudent(si);
else {
addsrv.saveStudent(si);
}
return true;
}
@RequestMapping("/findstudbyid")
@ResponseBody
public StudentInfo findstudbyid(Integer id) throws Exception
{
return addsrv.findStudentById(id);
}
@RequestMapping("/findstud")
@ResponseBody
@Cacheable
public PageInfo findstud(@RequestBody Map map) throws Exception
{
System.out.println("map==="+map);
Integer page = 1;
Integer rows = 4;
String name = null;
String age1 = null;
String age2 = null;
if(map != null)
{
Object temp = map.get("currentpage");
if(temp != null && !"".equals(temp))
page = new Integer(temp.toString());
temp = map.get("pagesize");
if(temp != null && !"".equals(temp))
rows = new Integer(temp.toString());
name = (String)map.get("name");
age1 = (String)map.get("age1");
age2 = (String)map.get("age2");
}
return addsrv.findStudent(page, rows, name,age1,age2);
}
@RequestMapping("/deletestud")
@ResponseBody
@CacheEvict
public Boolean deletestud(String ids)
{
if(ids != null)
{
String[] dim = ids.split(",");
for(String s:dim)
{
addsrv.deleteStudent(new Integer(s));
}
}
return true;
}
@RequestMapping("/loadtype")
@ResponseBody
public List<TypeInfo> getTypeJson()
{
List<TypeInfo> rtn = getFirstNode();
return rtn;
}
@RequestMapping("/loadtypechild")
@ResponseBody
public List<TypeInfo> getTypeByPid(Integer pid)
{
System.out.println("pid==="+pid);
List<TypeInfo> rtn = addsrv.getTypeList(pid);
return rtn;
}
private List<TypeInfo> getFirstNode()
{
TypeInfo root = addsrv.getRootType();
List<TypeInfo> firstList = addsrv.getTypeList(root.getId());
for(TypeInfo ti:firstList)
recurseNode(ti);
return firstList;
}
private void recurseNode(TypeInfo ti)
{
List<TypeInfo> children = addsrv.getTypeList(ti.getId());
System.out.println("ti.id"+ti.getId()+",children="+children);
if(children==null || children.size()==0)
return;
ti.setChildren(children);
for(TypeInfo chd:children)
{
recurseNode(chd);
}
}
@RequestMapping("/savetype")
@ResponseBody
public Boolean savetype(@RequestBody TypeInfo ti)
{
try {
Integer id = ti.getId();
if(id != null)
addsrv.updateType(ti);
else {
addsrv.saveType(ti);
}
return true;
} catch (Exception e) {
return false;
}
}
@RequestMapping("/upload")
@ResponseBody
public Integer upload(HttpServletRequest req)
{
try {
FileInfo fi = uploadFile(req);
System.out.println(fi);
addsrv.saveFile(fi);
return fi.getId();
} catch (Exception e) {
return 0;
}
}
public FileInfo uploadFile(HttpServletRequest req)
{
if(!(req instanceof MultipartHttpServletRequest))
return null;
MultipartHttpServletRequest mreq = (MultipartHttpServletRequest)req;
MultipartFile multipartFile = mreq.getFile("file");
try
{
InputStream is = multipartFile.getInputStream();
byte[] bytes = FileCopyUtils.copyToByteArray(is);
FileInfo fi = new FileInfo();
fi.setName(multipartFile.getName());
fi.setContextType(multipartFile.getContentType());
fi.setLength(new Long(multipartFile.getBytes().length));
fi.setContent(bytes);
return fi;
}
catch(Exception e)
{
e.printStackTrace();
}
return null;
}
}
前端VUE
<template>
<el-container>
<el-aside width="200px">
<el-tree ref="tree"
:data="data"
lazy
show-checkbox
node-key="id"
check-strictly
:load="loadnode"
:props="defaultProps"
@node-click="nodeclick">
</el-tree>
</el-aside>
<el-main>
<el-form :model="typeinfo" class="demo-form-inline">
<el-form-item label="ID">
<el-input v-model="typeinfo.id" readonly></el-input>
</el-form-item>
<el-form-item label="分类名称">
<el-input v-model="typeinfo.label" placeholder="分类名称"></el-input>
</el-form-item>
<el-form-item label="序号">
<el-input v-model="typeinfo.seqno" placeholder="序号"></el-input>
</el-form-item>
<el-form-item label="父ID">
<el-input v-model="typeinfo.pid" readonly></el-input>
</el-form-item>
<el-form-item label="上传">
<el-upload
class="upload-demo"
action="http://localhost:6060/upload"
:on-preview="handlePreview"
:on-remove="handleRemove"
:on-success="uploadok"
:file-list="fileList"
list-type="picture">
<el-button size="small" type="primary">点击上传</el-button>
<div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div>
</el-upload>
</el-form-item>
<el-image
style="width: 100px; height: 100px"
:src="img+typeinfo.imgid"></el-image>
<el-form-item>
<el-button type="primary" @click="dosave">保存</el-button>
<el-button type="primary" @click="dochildsave">添加节点</el-button>
</el-form-item>
</el-form>
</el-main>
</el-container>
</template>
<script>
import axios from 'axios'
export default {
data() {
return {
data:[],//树对象数据模型
defaultProps: {//树对象属性对应关系
children: 'children',
label: 'label'
},
typeinfo: {//商品分类实体对象
id:'',
pid:'',
label: '',
seqno: '',
imgid:''
},
fileList: [],
img:'http://localhost:6060/downimg?id='
}
},
methods: {
handleRemove(file, fileList) {
console.log(fileList);
},
handlePreview(file) {
console.log(file);
},
uploadok(response, file, fileList){
this.typeinfo.imgid=response;
},
loadnode(node,resolve){
//如果展开第一级节点,从后台加载一级节点列表
if(node.level==0)
{
this.loadfirstnode(resolve);
}
//如果展开其他级节点,动态从后台加载下一级节点列表
if(node.level>=1)
{
this.loadchildnode(node,resolve);
}
},
//加载第一级节点
loadfirstnode(resolve){
axios.get('http://localhost:6060/loadtype')
.then(function(resp){
resolve(resp.data);
})
},
//刷新树组件
refreshtree(){
var _this = this;
axios.get('http://localhost:6060/loadtype')
.then(function(resp){
_this.data = resp.data;
})
},
//加载节点的子节点集合
loadchildnode(node,resolve){
axios.get('http://localhost:6060/loadtypechild?pid='+node.data.id)
.then(function(resp){
resolve(resp.data);
})
},
//点击节点上触发的事件,传递三个参数,数据对象使用第一个参数
nodeclick(data,dataObj,self)
{
//alert(data.label+",id="+data.id);
this.typeinfo.id=data.id;
this.typeinfo.pid=data.pid;
this.typeinfo.label=data.label;
this.typeinfo.seqno=data.seqno;
this.typeinfo.imgid=data.imgid;
},
//保存分类方法
dosave()
{
var _this = this;
axios.post('http://localhost:6060/savetype',this.typeinfo)
.then(function(resp){
if(resp.data)
_this.refreshtree();
})
},
//保存子分类方法
dochildsave()
{
//判断左侧树组件是否选择了一个节点
var cnt=this.$refs['tree'].getCheckedNodes().length;
if(cnt!=1)
{
this.$message('必须选择唯一父节点');
return;
}
//通过this.$refs['tree']获取树对象,其中tree是树组件的ref属性
var dataObj = this.$refs['tree'].getCheckedNodes()[0];
this.typeinfo.id='';
this.typeinfo.pid=dataObj.id;
var _this = this;
axios.post('http://localhost:6060/savetype',this.typeinfo)
.then(function(resp){
if(resp.data)
_this.refreshtree();
})
}
}
}
</script>
后台代码
https://pan.baidu.com/s/1-CIzMewuu0AfGFgvJ2HFNw 提取码sq4n
前台代码
https://pan.baidu.com/s/1XD2dAXR0zj1zp5DtibWE-Q 提取码9g94