前言
链接:https://pan.baidu.com/s/1lCcPvYYNWncb6lbvrZdeVg
提取码:0tf1
环境
SpringBoot - 2.5.12
MongoDB - 5.0.6
代码实现
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- mongodb -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<!-- lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<!-- hutool -->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>4.5.1</version>
</dependency>
server:
port: 31091
spring:
servlet:
multipart:
max-file-size: 100MB
data:
mongodb:
host: 127.0.0.1
port: 27017
database: admin
username: root
password: sunday
fileUploadService:
impl: fileMongoServiceImpl
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.gridfs.GridFSBucket;
import com.mongodb.client.gridfs.GridFSBuckets;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MongoConfig {
@Value("${spring.data.mongodb.database}")
private String db;
@Bean
public GridFSBucket getGridFSBucket(MongoClient mongoClient){
MongoDatabase mongoDatabase = mongoClient.getDatabase(db);
return GridFSBuckets.create(mongoDatabase);
}
}
FileUploadController.java
import com.coisini.mongodb.model.ResponseMessage;
import com.coisini.mongodb.service.FileUploadService;
import com.coisini.mongodb.vo.FileExportVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
@Slf4j
@RestController
@RequestMapping("/file")
public class FileUploadController {
@Resource(name="${fileUploadService.impl}")
private FileUploadService fileUploadService;
@PostMapping("/upload")
public ResponseMessage<?> uploadFile(@RequestParam(value = "file") MultipartFile file) {
try {
return ResponseMessage.ok("上传成功", fileUploadService.uploadFile(file));
} catch (Exception e) {
log.error("文件上传失败:", e);
return ResponseMessage.error(e.getMessage());
}
}
@PostMapping("/uploadFiles")
public ResponseMessage<?> uploadFile(@RequestParam(value = "files") List<MultipartFile> files) {
try {
return ResponseMessage.ok("上传成功", fileUploadService.uploadFiles(files));
} catch (Exception e) {
return ResponseMessage.error(e.getMessage());
}
}
@GetMapping("/download/{fileId}")
public ResponseEntity<Object> fileDownload(@PathVariable(name = "fileId") String fileId) {
FileExportVo fileExportVo = fileUploadService.downloadFile(fileId);
if (Objects.nonNull(fileExportVo)) {
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "fileName=\"" + fileExportVo.getFileName() + "\"")
.header(HttpHeaders.CONTENT_TYPE, fileExportVo.getContentType())
.header(HttpHeaders.CONTENT_LENGTH, fileExportVo.getFileSize() + "").header("Connection", "close")
.body(fileExportVo.getData());
} else {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body("file does not exist");
}
}
@DeleteMapping("/remove/{fileId}")
public ResponseMessage<?> removeFile(@PathVariable(name = "fileId") String fileId) {
fileUploadService.removeFile(fileId);
return ResponseMessage.ok("删除成功");
}
}
import com.coisini.mongodb.vo.FileExportVo;
import org.springframework.web.multipart.MultipartFile;
import java.util.List;
public interface FileUploadService {
FileExportVo uploadFile(MultipartFile file) throws Exception;
List<FileExportVo> uploadFiles(List<MultipartFile> files);
FileExportVo downloadFile(String fileId);
void removeFile(String fileId);
}
FileMongoServiceImpl.java
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.IdUtil;
import com.coisini.mongodb.model.MongoFile;
import com.coisini.mongodb.repository.MongoFileRepository;
import com.coisini.mongodb.service.FileUploadService;
import com.coisini.mongodb.util.MD5Util;
import com.coisini.mongodb.vo.FileExportVo;
import com.mongodb.client.gridfs.GridFSBucket;
import com.mongodb.client.gridfs.GridFSDownloadStream;
import com.mongodb.client.gridfs.model.GridFSFile;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.bson.types.Binary;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.gridfs.GridFsResource;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
@Slf4j
@Service("fileMongoServiceImpl")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class FileMongoServiceImpl implements FileUploadService {
private final MongoFileRepository mongoFileRepository;
private final MongoTemplate mongoTemplate;
private final GridFsTemplate gridFsTemplate;
private final GridFSBucket gridFSBucket;
@Override
public List<FileExportVo> uploadFiles(List<MultipartFile> files) {
return files.stream().map(file -> {
try {
return this.uploadFile(file);
} catch (Exception e) {
log.error("文件上传失败", e);
return null;
}
}).filter(Objects::nonNull).collect(Collectors.toList());
}
@Override
public FileExportVo uploadFile(MultipartFile file) throws Exception {
if (file.getSize() > 16777216) {
return this.saveGridFsFile(file);
} else {
return this.saveBinaryFile(file);
}
}
@Override
public FileExportVo downloadFile(String fileId) {
Optional<MongoFile> option = this.getBinaryFileById(fileId);
if (option.isPresent()) {
MongoFile mongoFile = option.get();
if(Objects.isNull(mongoFile.getContent())){
option = this.getGridFsFileById(fileId);
}
}
return option.map(FileExportVo::new).orElse(null);
}
@Override
public void removeFile(String fileId) {
Optional<MongoFile> option = this.getBinaryFileById(fileId);
if (option.isPresent()) {
if (Objects.nonNull(option.get().getGridFsId())) {
this.removeGridFsFile(fileId);
} else {
this.removeBinaryFile(fileId);
}
}
}
public void removeBinaryFile(String fileId) {
mongoFileRepository.deleteById(fileId);
}
public void removeGridFsFile(String fileId) {
MongoFile mongoFile = mongoTemplate.findById(fileId, MongoFile.class );
if(Objects.nonNull(mongoFile)){
Query deleteFileQuery = new Query().addCriteria(Criteria.where("filename").is(mongoFile.getGridFsId()));
gridFsTemplate.delete(deleteFileQuery);
Query deleteQuery = new Query(Criteria.where("id").is(fileId));
mongoTemplate.remove(deleteQuery, MongoFile.class);
}
}
public FileExportVo saveBinaryFile(MultipartFile file) throws Exception {
String suffix = getFileSuffix(file);
MongoFile mongoFile = mongoFileRepository.save(
MongoFile.builder()
.fileName(file.getOriginalFilename())
.fileSize(file.getSize())
.content(new Binary(file.getBytes()))
.contentType(file.getContentType())
.uploadDate(new Date())
.suffix(suffix)
.md5(MD5Util.getMD5(file.getInputStream()))
.build()
);
return new FileExportVo(mongoFile);
}
public FileExportVo saveGridFsFile(MultipartFile file) throws Exception {
String suffix = getFileSuffix(file);
String gridFsId = this.storeFileToGridFS(file.getInputStream(), file.getContentType());
MongoFile mongoFile = mongoTemplate.save(
MongoFile.builder()
.fileName(file.getOriginalFilename())
.fileSize(file.getSize())
.contentType(file.getContentType())
.uploadDate(new Date())
.suffix(suffix)
.md5(MD5Util.getMD5(file.getInputStream()))
.gridFsId(gridFsId)
.build()
);
return new FileExportVo(mongoFile);
}
public String storeFileToGridFS(InputStream in, String contentType){
String gridFsId = IdUtil.simpleUUID();
gridFsTemplate.store(in, gridFsId , contentType);
return gridFsId;
}
public Optional<MongoFile> getBinaryFileById(String id) {
return mongoFileRepository.findById(id);
}
public Optional<MongoFile> getGridFsFileById(String id){
MongoFile mongoFile = mongoTemplate.findById(id , MongoFile.class );
if(Objects.nonNull(mongoFile)){
Query gridQuery = new Query().addCriteria(Criteria.where("filename").is(mongoFile.getGridFsId()));
try {
GridFSFile fsFile = gridFsTemplate.findOne(gridQuery);
GridFSDownloadStream in = gridFSBucket.openDownloadStream(fsFile.getObjectId());
if(in.getGridFSFile().getLength() > 0){
GridFsResource resource = new GridFsResource(fsFile, in);
mongoFile.setContent(new Binary(IoUtil.readBytes(resource.getInputStream())));
return Optional.of(mongoFile);
}else {
return Optional.empty();
}
}catch (IOException e){
log.error("获取MongoDB大文件失败", e);
}
}
return Optional.empty();
}
private String getFileSuffix(MultipartFile file) {
String suffix = "";
if (Objects.requireNonNull(file.getOriginalFilename()).contains(".")) {
suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
}
return suffix;
}
}
import com.coisini.mongodb.model.MongoFile;
import org.springframework.data.mongodb.repository.MongoRepository;
public interface MongoFileRepository extends MongoRepository<MongoFile, String> {
}
import lombok.Builder;
import lombok.Data;
import org.bson.types.Binary;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import java.util.Date;
@Document
@Builder
@Data
public class MongoFile {
@Id
public String id;
public String fileName;
public long fileSize;
public Date uploadDate;
public String md5;
private Binary content;
public String contentType;
public String suffix;
public String description;
private String gridFsId;
}
public class ResponseMessage<T> {
private String status;
private String message;
private T data;
}
import java.util.Objects;
@Data
public class FileExportVo {
private String fileId;
private String fileName;
private String contentType;
private String suffix;
private long fileSize;
@JsonIgnore
private byte[] data;
public FileExportVo(MongoFile mongoFile) {
BeanUtil.copyProperties(mongoFile, this);
if (Objects.nonNull(mongoFile.getContent())) {
this.data = mongoFile.getContent().getData();
}
this.fileId = mongoFile.getId();
}
}
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class MD5Util {
public static String getMD5(InputStream is) throws NoSuchAlgorithmException, IOException {
StringBuffer md5 = new StringBuffer();
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] dataBytes = new byte[1024];
int nread = 0;
while ((nread = is.read(dataBytes)) != -1) {
md.update(dataBytes, 0, nread);
};
byte[] mdbytes = md.digest();
for (int i = 0; i < mdbytes.length; i++) {
md5.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16).substring(1));
}
return md5.toString();
}
}
测试
源码
- End -
- 个人笔记 -
- 仅供参考 -
|