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依赖



    org.springframework.boot
    spring-boot-starter-data-mongodb

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> 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 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 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.编写测试页面





文件上传





	
序号 图片名称 图片缩略图 操作

 

你可能感兴趣的:(Spring,boot)