2023 mongodb GridFS整合SpringBoot
以下是一个使用Spring Boot整合MongoDB的GridFSBucket的简单例子。
首先,在pom.xml
中添加依赖:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<!-- 其他依赖 -->
</dependencies>
然后,配置application.properties
或application.yml
文件:
spring.data.mongodb.uri=mongodb://username:password@localhost:27017/your_database
接下来,创建一个服务类来处理文件的存储和检索:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import com.mongodb.client.gridfs.GridFSBucket;
import com.mongodb.client.gridfs.GridFSBuckets;
import org.bson.types.ObjectId;
import org.springframework.web.multipart.MultipartFile;
import java.io.InputStream;
import java.net.URI;
import java.nio.file.Path;
import java.nio.file.Paths;
@Service
public class StorageService {
@Autowired
private GridFSBucket gridFSBucket;
public String storeFile(MultipartFile file) {
try (InputStream inputStream = file.getInputStream()) {
ObjectId fileId = gridFSBucket.uploadFromStream(file.getOriginalFilename(), inputStream);
return fileId.toHexString();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public Resource loadFile(String fileId) {
try {
GridFSBucket bucket = GridFSBuckets.create(gridFSBucket.getBucket().getDatabase());
com.mongodb.client.gridfs.model.GridFSFile file = bucket.find(new ObjectId(fileId)).first();
if (file != null) {
return new UrlResource(file.getDownloadLink().toURI());
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
最后,创建一个控制器来处理文件的上传和下载请求:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.
评论已关闭