Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
256 views
in Technique[技术] by (71.8m points)

Springboot 与Mongodb

我在github找了个Springboot 与Mongodb的项目,项目的Springboot版本是1.5.2.
这个项目是简单的商品管理系统,它用mongodb存储商品图片。
当点击下图中的编辑按钮时:
999.png

它就跳转到处理方法itemEditGet,此处商品itm的id和图片存储在mongodb的id是相同的,这个方法负责根据item.getId是否为0判断是在执行增加商品操作还是编辑商品信息操作。

@Controller
public class ItemController {

   String imageName = null;
    File getFile = null;

public static final String ROOT = "src/main/resources/static/img/item/";

    @GetMapping("/user/itemEdit")
    public String itemEditGet(Model model, Item item) {
        //省略一部分
        if (item.getId() != 0) {
            Item item1 = itemMapper.findById(item);
            String id = String.valueOf(item.getId());
            // 商品item的id与放在mongodb的图片id是相同的
            GridFSDBFile fileById = mongoUtil.getFileById(id);

            if (fileById != null) {
                StringBuilder sb = new StringBuilder(ROOT);
                imageName = fileById.getFilename();
                sb.append(imageName);
                try {
                    getFile = new File(sb.toString());
                    fileById.writeTo(getFile);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                //图片名称
                item1.setImage(imageName);
            }
            model.addAttribute("item", item1);
        }
        return "item/itemEdit";
    }
    
@PostMapping("/user/itemEdit")
    public String itemEditPost(Model model, HttpServletRequest request, @RequestParam("file") MultipartFile file, Item item, HttpSession httpSession) {
        //根据时间和随机数生成id
        Date date = new Date();
        item.setCreated(date);
        item.setUpdated(date);
        item.setBarcode("");
        item.setImage("");
        int rannum = 0;
        if (file.isEmpty()) {
            System.out.println("图片未上传");
        } else {
            try {
                Path path = Paths.get(ROOT, file.getOriginalFilename());
                File tempFile = new File(path.toString());
                if (!tempFile.exists()) {
                    Files.copy(file.getInputStream(), path);
                }
                LinkedHashMap<String, Object> metaMap = new LinkedHashMap<String, Object>();
                String id = null;
                if (item.getId() != 0) {
                    id = String.valueOf(item.getId());
                } else {
                    Random random = new Random();
                    rannum = (int) (random.nextDouble() * (99999 - 10000 + 1)) + 1000;// 获取5位随机数
                    id = String.valueOf(rannum);
                }
                metaMap.put("contentType", "jpg");
                metaMap.put("_id", id);
                mongoUtil.uploadFile(tempFile, id, metaMap);
                tempFile.delete();
                getFile.delete();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            System.out.println("get File by Id Success");
        }

        if (item.getId() != 0) {
            itemMapper.update(item);
        } else {

            item.setId(rannum);
            itemMapper.insert(item);
        }
        return "redirect:itemManage_0_0_0";
    }
    
    @GetMapping(value = "/{filename:.+}")
    @ResponseBody
    public ResponseEntity<?> getFile() {
        try {
            return ResponseEntity.ok(resourceLoader.getResource("file:" + Paths.get(ROOT, imageName).toString()));
        } catch (Exception e) {
            return ResponseEntity.notFound().build();
        }
    }
}

跳转到的编辑页面item/itemEdit是这样的:
31313.png

其中该页面显示图片的html代码是这样的:

<div id="imageCell" class="form-group"><label class="col-sm-2 control-label">图片:</label>
   <div class="col-sm-10">
      <img  th:src="@{'/'+${item.image}}" height="250px" width="200px"  />
       <button id="imageCellBut" type="button" class="btn btn-white btn-sm">&nbsp;&nbsp;&nbsp;&nbsp;修改&nbsp;&nbsp;&nbsp;&nbsp;</button>
    </div>
</div>

这个显示图片的部分对应的是getFile方法,它是返回项目里src/main/resources/static/img/item/imageName位置的图片

项目的Mongodb相关类是这样写的:

public class MongoUtil {

    String dbName = "jesper";
    String collectionName = "myimage";

    private static class MongoConnectionHolder {
        public static Mongo mongo = new MongoClient("127.0.0.1", 27017);
    }

    private Mongo getMongo() {
        return MongoConnectionHolder.mongo;
    }
//map存储文件的相关信息,例如文件类型。
    public void uploadFile(File file, String id, LinkedHashMap<String, Object> map) {
        
        try {
           
            Mongo mongo = getMongo();
            DB db = mongo.getDB(dbName);
            GridFS gridFS = new GridFS(db, collectionName);

            // 创建gridfsfile文件
            GridFSFile gridFSFile = gridFS.createFile(file);
            //判断是否已经存在文件,如果存在则先删除
            GridFSDBFile gridFSDBFile = getFileById(id);
            if (gridFSDBFile != null) {
                deleteFile(id);
            }
            //将文件属性设置到
            gridFSFile.put("_id", id);
            //循环设置文件属性
            if (map != null && map.size() > 0) {
                for (String key : map.keySet()) {
                    gridFSFile.put(key, map.get(key));
                }
            }
            //保存上传
            gridFSFile.save();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    // 删除文件
    public void deleteFile(String id) {

        try {
            //获得mongoDB数据库连接。
            Mongo mongo = getMongo();
            //获得库
            DB db = mongo.getDB(dbName);
            //获得子集
            GridFS gridFS = new GridFS(db, collectionName);
            //删除文件
            DBObject query = new BasicDBObject("_id", id);
            gridFS.remove(query);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

 

    /**
     * @param id                 :文件Id
     * @return GridFSDBFile
     * @MethodName    : getFileById
     * @Description    : 根据Id获得文件
     */
    public GridFSDBFile getFileById(String id) {
        GridFSDBFile gridFSDBFile = null;
        try {
            //获得mongoDB数据库连接。
            Mongo mongo = getMongo();
            //获得库
            DB db = mongo.getDB(dbName);
            //获得子集
            GridFS gridFS = new GridFS(db, collectionName);
            //获得文件
            DBObject query = new BasicDBObject("_id", id);
            gridFSDBFile = gridFS.findOne(query);

        } catch (Exception e) {
            e.printStackTrace();
        }
        //返回数据
        return gridFSDBFile;
    }

我本想参照着这个项目写一遍,但是我的springboot版本是2.3.1,该版本好像没有 GridFSDBFile 这个类的。
我想问一下如果是参照这种思路,我该怎么写MongoDb的上传图片到mongodb以及在编辑页面里显示mongodb里对应的图片。或者有更好的方式?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

参考一下这个:点击跳转


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.6k users

...