MongoDB文件上传下载操作工具类和summernote富文本编辑器的图片上传和回显

 MongoDB数据库操作文件上传下载的工具类:

(MongoDB数据库的集合名类似SQL中的表)

import com.mongodb.DB;
import com.mongodb.gridfs.GridFS;
import com.mongodb.gridfs.GridFSDBFile;
import com.mongodb.gridfs.GridFSInputFile;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.UUID;

/**
 * MongoDB数据库文件操作工具类
 * @author lyk
 * @date 2018-7-20
 */
public class MongoDBFileUtils {


    /**
     * @Describe: 保存文件到指定MongoDB的集合中
     * @param multipartFile 文件对象
     * @param collectionName 集合名,相当于Sql的表
     * @param  mongoTemplate
     * @return 新文件名(唯一ID)
     */
    public static String saveFile(MultipartFile multipartFile, String collectionName,MongoTemplate mongoTemplate) throws IOException {

        //获取文件原始名称
        String originalFilename = multipartFile.getOriginalFilename();
        // 获取文件后缀名
        String ext = originalFilename.substring(originalFilename.lastIndexOf("."));
        //设置新名称(UUID唯一)
        String newName = UUID.randomUUID().toString().replace("-","")+ext;

        //创建临时文件对象,把MultipartFile转换成File类型
        File tempFile =File.createTempFile("temp",ext);
        multipartFile.transferTo(tempFile);

        //获取MongoDB数据库对象
        DB db = mongoTemplate.getDb();

        // 获取该数据库的集合的GFS
        GridFS gridFS = new GridFS(db,collectionName);

        //创建该集合的GFS对象
        GridFSInputFile gridFSInputFile = gridFS.createFile(tempFile);

        //为filename属性赋值
        gridFSInputFile.put("filename", newName);
        //为contentType属性赋值
        gridFSInputFile.put("contentType",ext);

        //执行保存
        gridFSInputFile.save();

        //返回新文件名(唯一)
        return newName;
    }


    /**
     * @Desc 获取GridFSDBFile文件
     * @param fileName
     * @param collectionName
     * @param mongoTemplate
     */
    public static GridFSDBFile getGfsFile(String fileName,String collectionName,MongoTemplate mongoTemplate) {

        //获取MongoDB数据库对象
        DB db = mongoTemplate.getDb();

        //获取该数据库的集合的GFS
        GridFS gridFS = new GridFS(db,collectionName);

        //根据唯一的文件名获取GFS文件对象
        GridFSDBFile gridFSDBFile = gridFS.findOne(fileName);

        return gridFSDBFile;
    }


    /**
     * @Desc 把GridFSDBFile对象输出到页面
     * @param gridFSDBFile
     * @param response
     */
    public static void outPutGfsFile(GridFSDBFile gridFSDBFile,HttpServletResponse response) throws IOException {
            if (gridFSDBFile != null) {

                OutputStream sos = response.getOutputStream();
                response.setContentType("application/octet-stream");

                // 获取原文件名
                String name = (String) gridFSDBFile.get("filename");
                String newFileName = new String(name.getBytes("GBK"), "ISO8859-1");

                // 设置下载文件名
                response.addHeader("Content-Disposition", "attachment; filename=\"" + newFileName + "\"");

                // 向客户端输出文件
                gridFSDBFile.writeTo(sos);
                sos.flush();
                sos.close();
            }
    }


    /**
     * 根据文件名ID和集合名获取文件,并向页面输出
     * @param fileName
     * @param collectionName
     * @param response
     * @param mongoTemplate
     * @throws IOException
     */
    public static void outFile(String fileName,String collectionName,HttpServletResponse response,MongoTemplate mongoTemplate) throws IOException {

        GridFSDBFile gridFSDBFile = getGfsFile(fileName,collectionName,mongoTemplate);
        outPutGfsFile(gridFSDBFile,response);

    }


}





Controller示例:

    
@Controller
@RequestMapping("noticeManage")
public class NoticeManageController {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 把富文本编辑器里的图片保存到MongoDB数据库
     * @param content_image
     * @return
     */
    @RequestMapping("fileUpload")
    @ResponseBody
    public HashMap fileUpload(MultipartFile content_image) {
        HashMap map = new HashMap();
        try {
            String fileName = MongoDBFileUtils.saveFile(content_image, "content_image", mongoTemplate);
            String path = "/noticeManage/showContentImage?fileName="+fileName;
            map.put("path",path);
            return map;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }

    }


    /**
     * @Description 从mongodb中获取图片
     * @param fileName 文件名
     * @param response
     * @author Liuyukang
     * @Date 2018-7-9
     */
    @RequestMapping(value = "showContentImage")
    public void showImageLarge(String fileName,HttpServletResponse response)  {
        try {
            MongoDBFileUtils.outFile(fileName,"content_image",response,mongoTemplate);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

JS示例(summernote富文本编辑器里的图片上传和回显):

<link rel="stylesheet" type="text/css" href="${BASE_FRONT}/app/dist/summernote.css"/>
<script type="text/javascript" charset="utf-8" src="${BASE_FRONT}/app/dist/summernote.js"></script>
<script type="text/javascript" charset="utf-8" src="${BASE_FRONT}/app/dist/lang/summernote-zh-CN.js"></script>
    <script>
        $(function(){
            $('.summernote').summernote({
                lang: 'zh-CN',
                height: 150,
                //调用图片上传
                callbacks: {
                    onImageUpload: function (files) {

                        var data = new FormData();
                        data.append("content_image", files[0]);
                        $.ajax({
                            data: data,
                            type: "POST",
                            url: "/noticeManage/fileUpload", 
                            //图片上传出来的url,返回的是图片上传后的路径,http格式
                            cache: false,
                            contentType: false,
                            processData: false,
                            dataType: "json",
                            success: function (data) {
                                //data是返回的hash,key之类的值,key是定义的文件名
                                $('.summernote').eq(0).summernote('insertImage', data.path);//新增窗口的富文本编辑器
                                $('.summernote').eq(1).summernote('insertImage', data.path);//编辑窗口的富文本编辑器
                            },
                            error: function () {
                                alert("上传失败");
                            }
                        });
                    }
                }
            });

        });
    </script>

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值