Upload pictures to the Mongo database; Mongo database download pictures from the display to the front

/**
     * Upload an image file saved to the database mongo
     * @param doc
     * @Param directory parent file is located
     * @param request
     * @return
     */
    @PostMapping("/uploaddoc")
    public ErrorMessage uploaddoc(MultipartFile doc, @RequestParam String parent, HttpServletRequest request) throws IOException {
        ErrorMessage result = new ErrorMessage();
        MongoDatabase db = mongoTemplate.getDb();
        Bucket GridFSBucket = GridFSBuckets.create (db, "docs"); // open an object created when there is no 
        GridFSUploadStream uploadStream = bucket.openUploadStream (doc.getOriginalFilename ());
        uploadStream.write(doc.getBytes());
        System.out.println(uploadStream.getObjectId());
        uploadStream.close();
      return result;
    }   
/**
     * Download a picture file is displayed in the front <img> in
     */
    @GetMapping("/downloadImage/{uuid}")
    public void downloadImage(@PathVariable String uuid, HttpServletResponse response) throws IOException {
//        response.setContentType("image/jpg");//显示,用不着设置它
        MongoDatabase db = mongoTemplate.getDb();
        Bucket GridFSBucket = GridFSBuckets.create (db, "docs"); // open an existing object of
         // uuid as a picture file Id in Mongo database 
        GridFSDownloadStream downloadStream = bucket.openDownloadStream ( new new ObjectId (uuid));
        OutputStream outputStream = response.getOutputStream();
        IOUtils.copy(downloadStream, outputStream);
        downloadStream.close();
        outputStream.close();
    }
A front end part of the code // 
// http: // localhost: 8080 / downloadImage / 5dca4f1d911b52478896430e is accessing the backend interface

// 5dca4f1d911b52478896430e object is ObjectId GridFs

<img id="img1" src=""> <button onclick="showImage()">get Image</button> <script> function showImage() { document.getElementById('img1').src='http://localhost:8080/downloadImage/5dca4f1d911b52478896430e'; } </script>

 

Guess you like

Origin www.cnblogs.com/muhu08120559/p/11842162.html
Recommended