溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

如何使用Springboot整合GridFS實(shí)現(xiàn)文件操作

發(fā)布時(shí)間:2021-10-23 13:41:04 來源:億速云 閱讀:159 作者:iii 欄目:開發(fā)技術(shù)

本篇內(nèi)容介紹了“如何使用Springboot整合GridFS實(shí)現(xiàn)文件操作”的有關(guān)知識(shí),在實(shí)際案例的操作過程中,不少人都會(huì)遇到這樣的困境,接下來就讓小編帶領(lǐng)大家學(xué)習(xí)一下如何處理這些情況吧!希望大家仔細(xì)閱讀,能夠?qū)W有所成!

目錄
  • GridFsOperations,實(shí)現(xiàn)GridFS文件上傳下載刪除

    • 上傳下載刪除功能實(shí)現(xiàn)

  • 測(cè)試

    • 上傳

    • 下載

    • 刪除

GridFsOperations,實(shí)現(xiàn)GridFS文件上傳下載刪除

最近學(xué)習(xí)GridFS,想用它整合springboot弄個(gè)文件的上傳下載。

網(wǎng)上查到的很多資料都是使用GridFsTemplate,還有GridFSBucket來實(shí)現(xiàn)的,需要各種額外配置Bean。但是看了spring-data-mongodb的官方文檔,以及示例代碼,他們只用到了GridFsOperations,無需其他任何配置。

然后就用GridFsOperations寫了個(gè)文件上傳下載的demo,用起來還是很方便的,給大家個(gè)參考。

上傳下載刪除功能實(shí)現(xiàn)

pom.xml

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>

application.properties

#文件上傳下載配置
spring.servlet.multipart.max-file-size=1024MB
spring.servlet.multipart.max-request-size=1024MB

FileController

package com.example.tryRedis.controller;
import static org.springframework.data.mongodb.core.query.Query.*;
import static org.springframework.data.mongodb.gridfs.GridFsCriteria.*;
import com.mongodb.client.gridfs.model.GridFSFile;
import io.swagger.v3.oas.annotations.Parameter;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.gridfs.GridFsOperations;
import org.springframework.data.mongodb.gridfs.GridFsResource;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
@RestController
@RequestMapping("/file")
public class FileController {
    @Autowired
    GridFsOperations gridFsOperations;
    //上傳文件
    @PostMapping(value = "/upload",consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public Map<String , ObjectId> upload(@Parameter @RequestPart(value = "file") MultipartFile file){
        //開始時(shí)間
        long begin = System.nanoTime();
        Map<String,ObjectId> map = new HashMap<>();
        try{
            InputStream streamForUpload = file.getInputStream();
            ObjectId objectId = gridFsOperations.store(streamForUpload,file.getOriginalFilename(),file.getContentType());
            //上傳結(jié)束
            long end = System.nanoTime();
            long time = end-begin;
            System.out.println("本次上傳共耗時(shí): "+ time);
            System.out.println("上傳成功!文件名: "+file.getOriginalFilename()+". 文件ID: "+objectId);
            map.put(file.getOriginalFilename(),objectId);
        }catch (Exception e){
            e.printStackTrace();
        }
        return map;
    }
    //查詢并下載文件
    @GetMapping("/download")
    public String download(String filename, HttpServletResponse response) throws IOException {
        //開始時(shí)間
        long begin = System.nanoTime();
        //查詢文件
        GridFSFile result  = gridFsOperations.findOne(query(whereFilename().is(filename)));
        GridFsResource gridFsResource= gridFsOperations.getResource(result);
        String contentType = gridFsResource.getContentType();
        System.out.println("contentType: "+contentType);
        System.out.println("filename: "+gridFsResource.getFilename());
        response.reset();
        response.setContentType(contentType);
        //注意: 如果沒有下面這行設(shè)置header, 結(jié)果會(huì)將文件的內(nèi)容作為響應(yīng)的 body 直接輸出在頁面上, 而不是下載文件
        response.setHeader("Content-Disposition","attachment;filename="+filename);  //指定下載文件名
        ServletOutputStream outputStream = response.getOutputStream();
        InputStream is = gridFsResource.getInputStream();
        byte[] bytes = new byte[1024];
        int len = 0;
        while ((len=is.read(bytes))!=-1){
            outputStream.write(bytes,0,len);
        }
        is.close();
        outputStream.close();
        //下載結(jié)束
        long end = System.nanoTime();
        long time = end-begin;
        System.out.println("本次下載共耗時(shí): "+ time);
        return contentType;
    }
    @DeleteMapping("/delete")
    public String deleteFile(@Parameter @RequestParam("filename") String filename){
        gridFsOperations.delete(query(whereFilename().is(filename)));
        return "delete success";
    }
}

測(cè)試

上傳

如何使用Springboot整合GridFS實(shí)現(xiàn)文件操作 如何使用Springboot整合GridFS實(shí)現(xiàn)文件操作

下載

紅色圈內(nèi)點(diǎn)擊download就可以下載啦。或者在地址欄直接輸入localhost:8080/file/download?filename=todo.txt 也可以直接下載文件(這里的todo.txt是我測(cè)試的文件,你們填自己上傳的文件名,不要忘了加上后綴名?。?/p>

如何使用Springboot整合GridFS實(shí)現(xiàn)文件操作

刪除

如何使用Springboot整合GridFS實(shí)現(xiàn)文件操作

上面這些上傳刪除功能測(cè)試的時(shí)候,大家也可以結(jié)合mongodb的數(shù)據(jù)庫去看看。

如何使用Springboot整合GridFS實(shí)現(xiàn)文件操作

“如何使用Springboot整合GridFS實(shí)現(xiàn)文件操作”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識(shí)可以關(guān)注億速云網(wǎng)站,小編將為大家輸出更多高質(zhì)量的實(shí)用文章!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI