1.官网下载MongoDB,下载完运行mongod服务
我的资源地址:https://download.csdn.net/download/rexueqingchun/11704418
2.application.properties配置MongoDB连接
#mongodb
spring.data.mongodb.uri=mongodb://localhost:27017/dhyjtest
dhyjtest:为自定义的数据库名
3.pom.xml添加MongoDB依赖
<!-- mongodb -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
4.编写MongoDb操作Service
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.gridfs.GridFsResource;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import com.mongodb.client.gridfs.GridFSBucket;
import com.mongodb.client.gridfs.GridFSBuckets;
import com.mongodb.client.gridfs.GridFSDownloadStream;
import com.mongodb.client.gridfs.model.GridFSFile;
@Service
public class MongoService {
@Autowired
private GridFsTemplate gridfsTemplate;
@Autowired
private MongoDbFactory mongoDbFactory;
/**
* 根据id查询文件
*/
public GridFSFile findFileById(Object id) throws Exception{
Query query = new Query();
query.addCriteria(Criteria.where("_id").is(id));
return gridfsTemplate.findOne(query);
}
/**
* 保存文件
* @param file
*/
public String saveFile(MultipartFile file) throws IOException {
String filename = file.getOriginalFilename();
String type=filename.substring(filename.lastIndexOf(".")-1,filename.length());
ObjectId id = gridfsTemplate.store(file.getInputStream(), UUID.randomUUID().toString().replaceAll("-","")+type, file.getContentType());
return id.toString();
}
/**
* 根据id删除文件
*/
public void deleteFileById(Object id){
Query query = new Query();
query.addCriteria(Criteria.where("_id").is(id));
gridfsTemplate.delete(query);
}
public byte[] downloadFile(String objectId, OutputStream out) throws Exception {
Query query = new Query();
query.addCriteria(Criteria.where("_id").is(objectId));
GridFSFile gridFSFile = gridfsTemplate.findOne(query);
GridFSBucket bucket = GridFSBuckets.create(mongoDbFactory.getDb());
GridFSDownloadStream in = bucket.openDownloadStream(gridFSFile.getObjectId());
GridFsResource resource = new GridFsResource(gridFSFile,in);
InputStream inputStream = resource.getInputStream();
byte[] f = getBytes(inputStream);
return f;
}
private byte[] getBytes(InputStream inputStream) throws Exception{
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] b = new byte[1024];
int i = 0;
while (-1!=(i=inputStream.read(b))){
bos.write(b,0,i);
}
return bos.toByteArray();
}
}
5.编写MongoDb测试Controller
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import cn.com.app.dao.JkconfigDao;
import cn.com.app.service.MongoService;
@Controller
public class TestController {
@Autowired
private MongoService mongoService;//mongo操作service
@Autowired
private JkconfigDao jkconfigDao;//自定义的数据保存查询dao
/**
* 图片列表
*/
@RequestMapping("/fileList")
public String fileList(Model model)throws Exception {
ist<Map<String, Object>> list = jkconfigDao.selectFile();
model.addAttribute("list", list);
return "file_list";
}
/**
* 保存图片
*/
@RequestMapping(value="/saveFile", method = RequestMethod.POST)
public String saveNews(@RequestParam("uploadImg") MultipartFile file,RedirectAttributes redirectAttributes)throws Exception {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Map<String,Object> param = new HashMap<>();
if(null != file){
//存文件返回id
String imgpathId = mongoService.saveFile(file);
//文件名
String fileName = file.getOriginalFilename();
param.put("file_path", imgpathId);
param.put("file_name", fileName);
}
param.put("id", UUID.randomUUID().toString().replaceAll("-",""));
param.put("rksj", format.format(new Date()));
jkconfigDao.saveInfo(param);
redirectAttributes.addFlashAttribute("message", "保存成功!");
return "redirect:/fileList";
}
/**
* 删除图片
*/
@RequestMapping(value="/deleteFile")
public String deleteFile(String id,String imgid)throws Exception {
if(id != null){
mongoService.deleteFileById(imgid);
}
Map<String,Object> param = new HashMap<>();
param.put("id", id);
jkconfigDao.deleteFile(param);
return "redirect:/fileList";
}
/**
* 获取mongo中的文件流,图片或者视频
*/
@RequestMapping(value = "/getMonImg")
public void getMonImg(HttpServletResponse response, HttpServletRequest request) throws Exception {
String id = request.getParameter("id");
OutputStream out = null;
try {
out = new BufferedOutputStream(response.getOutputStream());
byte[] f = mongoService.downloadFile(id,out);
out.write(f);
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
6.编写测试页面
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
<meta charset="UTF-8">
<title>文件上传</title>
<script src="/script/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
var message = $("#message").val();
if(message != ''){
alert(message);
}
})
function save(){
var file = $("#uploadImg").val();
if(file == ''){
alert("请选择文件");
}else{
$("#form").submit();
}
}
function deleteFile(id,imgid){
if (confirm("确定删除吗?")==true){
window.location.href='deleteFile?id='+id+"&imgid="+imgid;
}
}
</script>
</head>
<body style="text-align: center;">
<input type="hidden" id="message" name="message" th:value="${message}" />
<form id="form" action="saveFile" method="post" enctype="multipart/form-data">
<input type="file" id="uploadImg" name="uploadImg" value="选择文件" >
<input type="button" id="bc" value="保存" onclick="save()">
</form>
<div style="width: 100%;">
<table style="width: 50%;margin:0 auto;">
<tr>
<th>序号</th>
<th>图片名称</th>
<th>图片缩略图</th>
<th>操作</th>
</tr>
<tr th:each="item:${list}">
<td th:text="${itemStat.index+1}"></td>
<td th:text="${item.FILE_NAME}"></td>
<td><img th:src="${'getMonImg?id=' + item.FILE_PATH}" width="30px" height="30px;"></td>
<td><input type="button" value="删除" th:onclick="'deleteFile(\''+${item.ID}+'\',\''+${item.FILE_PATH}+'\')'"></td>
</tr>
</table>
</div>
</body>
</html>