SpringBoot配置MongoDB實現文件存儲

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>

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章