springboot2.x使用mongdb存储文件与预览图
2020-01-10 本文已影响0人
七枷琴子
使用类似七牛云图片预览似乎要一个域名才行,懒得弄域名就直接把文件放到MongoDB生成预览图了
引包,此处使用的版本是springboot的2.0.1.RELEASE
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
<version>2.1.7.RELEASE</version>
</dependency>
连接地址
image.png
上传接口,反正就是拿到个文件的流就行了
@PostMapping("/uploadfile")
public void fileUpLoadToTencentCloud(HttpServletRequest request,
HttpServletResponse response,
@ApiParam(name = "editormd-image-file", value = "文件数组", required = true)
@RequestParam(name = "editormd-image-file", required = true)
MultipartFile file) {
//文件上传
try {
request.setCharacterEncoding("utf-8");
response.setHeader("Content-Type", "text/html");
String fileName = TaleUtils.getFileKey(file.getOriginalFilename()).replaceFirst("/", "");
TFileModel tFileModel = FileManager.saveFile(file.getInputStream(), fileName);
response.getWriter().write("{\"success\": 1, \"message\":\"upload success\",\"url\":\"" + tFileModel.getId() + "\"}");
} catch (IOException e) {
e.printStackTrace();
}
}
获取预览流
/**
* 获取图片
*/
@GetMapping(value = "/showImage")
public void showImage(HttpServletRequest request, HttpServletResponse response, @RequestParam("id") String id) {
try {
OutputStream out = response.getOutputStream();
response.setContentType("image/jpg");
InputStream in = FileManager.getFileInputStream(id);
// 判断输入或输出是否准备好
if (in != null && out != null) {
int temp = 0;
// 开始拷贝
while ((temp = in.read()) != -1) {
// 边读边写
out.write(temp);
}
// 关闭输入输出流
in.close();
out.close();
}
} catch (IOException e) {
logger.error(e.toString());
}
}
文件管理工具类,使用静态方法调用,方便快捷
package cn.luischen.utils;
import cn.luischen.model.Enum.EnumFileStorageType;
import cn.luischen.model.TFileModel;
import cn.luischen.service.common.impl.FileBusinessService;
import cn.luischen.service.common.impl.MongoBusinessServiceImpl;
import com.mongodb.gridfs.GridFSDBFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
@Component
public class FileManager {
private static final Logger logger = LoggerFactory.getLogger(FileManager.class);
private static FileManager fileManager;
@Autowired
private MongoBusinessServiceImpl mongoBusinessService;
@Autowired
private FileBusinessService fileBusinessService;
//初始化静态参数
@PostConstruct
public void init() {
fileManager = this;
fileManager.mongoBusinessService = this.mongoBusinessService;
fileManager.fileBusinessService = this.fileBusinessService;
}
public static TFileModel saveFile(InputStream in, String name) {
return saveFile(in, name, 1);
}
public static TFileModel saveFile(InputStream in, String name, Integer type) {
if (type != null && !"".equals(type)) {
if (EnumFileStorageType.parse(type) == null) {
return null;
} else {
if (name == null || "".equals(name)) {
name = UUID.randomUUID().toString();
}
TFileModel fileModels = null;
TFileModel fileModel = new TFileModel();
fileModel.setFileName(name);
fileModel.setFileType(type);
try {
fileModel.setDeleteFlag(0);
fileModel.setFileLength(in.available());
ByteArrayOutputStream baosOutputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
while ((len = in.read(buffer)) > -1) {
baosOutputStream.write(buffer, 0, len);
}
baosOutputStream.flush();
InputStream stream1 = new ByteArrayInputStream(baosOutputStream.toByteArray());
InputStream stream2 = new ByteArrayInputStream(baosOutputStream.toByteArray());
String md5 = MD5Utils.getStreamMD5String(stream2);
String storeId = null;
storeId = saveToMongo(stream1);
if (storeId == null) {
return null;
}
fileModel.setFkStore(storeId);
fileModel.setFileCode(md5);
fileModels = fileManager.fileBusinessService.save(fileModel);
} catch (Exception var12) {
logger.error("系统错误", var12);
return null;
}
return fileModels != null ? fileModels : null;
}
} else {
return null;
}
}
private static String saveToMongo(InputStream in) {
Map<String, Object> map = new HashMap();
String id = UUID.randomUUID().toString();
map.put("id", id);
map.put("file", in);
fileManager.mongoBusinessService.saveFile(new Map[]{map});
return id;
}
public static TFileModel getFile(String pkFile) {
TFileModel fileModel = fileManager.fileBusinessService.queryById(pkFile);
return fileModel == null ? null : fileModel;
}
public static InputStream getFileInputStream(String pkFile) {
TFileModel fileModel = fileManager.fileBusinessService.queryById(pkFile);
return fileModel == null ? null : getFileInputStream(fileModel);
}
public static InputStream getFileInputStream(TFileModel fileModel) {
return findFromMongo(fileModel.getFkStore());
}
private static InputStream findFromMongo(String storeId) {
GridFSDBFile file = fileManager.mongoBusinessService.findFileById(storeId);
return file != null ? file.getInputStream() : null;
}
}
两个服务
package cn.luischen.service.common.impl;
import cn.luischen.dao.TFileMapper;
import cn.luischen.model.TFileModel;
import cn.luischen.utils.UUIDUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class FileBusinessService {
@Autowired
private TFileMapper tFileMapper;
public TFileModel save(TFileModel model) {
String uuid = UUIDUtil.getUUID();
model.setId(uuid);
int insert = tFileMapper.insert(model);
if (insert > 0) {
return model;
} else {
return null;
}
}
public TFileModel queryById(String pkFile) {
if (StringUtils.isNotBlank(pkFile)) {
TFileModel tFileModel = tFileMapper.selectByPrimaryKey(pkFile);
return tFileModel;
}
return null;
}
}
package cn.luischen.service.common.impl;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import com.mongodb.gridfs.GridFS;
import com.mongodb.gridfs.GridFSDBFile;
import com.mongodb.gridfs.GridFSInputFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.stereotype.Service;
import java.io.File;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
@Service
public class MongoBusinessServiceImpl {
private static final Logger logger = LoggerFactory.getLogger(MongoBusinessServiceImpl.class);
@Autowired
// @Qualifier("mongoDbFactory")
private MongoDbFactory factory;
@Autowired
private MongoClient mongoClient;
public List<Map<String, Object>> saveFile(Map... models) {
DB db = this.getDb();
for (int i = 0; i < models.length; ++i) {
try {
Map<String, Object> model = models[i];
String id = model.get("id") == null ? null : model.get("id") + "";
if (id == null) {
throw new RuntimeException("主键id为空!");
}
Object file = model.get("file");
GridFSInputFile gfsinput;
if (file instanceof File) {
File f = (File) file;
gfsinput = (new GridFS(db)).createFile(f);
} else if (file instanceof InputStream) {
InputStream is = (InputStream) file;
gfsinput = (new GridFS(db)).createFile(is);
} else {
if (!(file instanceof byte[])) {
throw new RuntimeException("不支持的文件数据类型");
}
byte[] bytes = (byte[]) ((byte[]) file);
gfsinput = (new GridFS(db)).createFile(bytes);
}
Iterator it = model.keySet().iterator();
while (it.hasNext()) {
String key = (String) it.next();
if (!"file".equals(key)) {
gfsinput.put(key, model.get(key));
}
}
gfsinput.save();
} catch (Exception var10) {
throw new RuntimeException(var10);
}
}
return Arrays.asList(models);
}
private DB getDb() {
return new DB(this.mongoClient, this.factory.getDb().getName());
}
public GridFSDBFile findFileById(String id) {
DB db = this.getDb();
GridFS gfs = new GridFS(db);
try {
DBObject query = new BasicDBObject("id", id);
GridFSDBFile gfsFile = gfs.findOne(query);
return gfsFile;
} catch (Exception var6) {
logger.error("系统错误", var6);
return null;
}
}
}
model表结构
public class TFileModel implements Serializable {
private String id;
private String fileName;
private Integer fileLength;
private Integer fileType;
private String fkStore;
private String creator;
private Date createTime;
private String updater;
private Date updateTime;
private Integer deleteFlag;
private String fileCode;
}
效果图,,还可以在工具类里加上存本地,存fastdfs之类的地方,先贴到这
image.png
附带两个工具类
package cn.luischen.utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.DigestUtils;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class MD5Utils {
private static final Logger logger = LoggerFactory.getLogger(MD5Utils.class);
private static MessageDigest messagedigest = null;
private static final char[] DIGITS = new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
public static String getFileMD5String(File file) {
try {
FileInputStream fileInputStream = new FileInputStream(file);
Throwable var2 = null;
String var3;
try {
var3 = getStreamMD5String(fileInputStream);
} catch (Throwable var13) {
var2 = var13;
throw var13;
} finally {
if (fileInputStream != null) {
if (var2 != null) {
try {
fileInputStream.close();
} catch (Throwable var12) {
var2.addSuppressed(var12);
}
} else {
fileInputStream.close();
}
}
}
return var3;
} catch (Exception var15) {
logger.error("系统错误", var15);
return null;
}
}
public static String getStreamMD5String(InputStream input) {
try {
byte[] buffer = new byte[8192];
int length;
while((length = input.read(buffer)) != -1) {
messagedigest.update(buffer, 0, length);
}
return new String(encode(messagedigest.digest()));
} catch (IOException var3) {
logger.error("系统错误", var3);
return null;
}
}
public static String getMD5String(String s) {
return DigestUtils.md5DigestAsHex(s.getBytes());
}
public static String getMD5String(byte[] bytes) {
return DigestUtils.md5DigestAsHex(bytes);
}
public static boolean checkPassword(String password, String md5PwdStr) {
String s = getMD5String(password);
return s.equals(md5PwdStr);
}
private MD5Utils() {
}
static {
try {
messagedigest = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException var1) {
logger.error("MD5 messagedigest初始化失败", var1);
}
}
public static char[] encode(byte[] data) {
int l = data.length;
char[] out = new char[l << 1];
int i = 0;
for(int var4 = 0; i < l; ++i) {
out[var4++] = DIGITS[(240 & data[i]) >>> 4];
out[var4++] = DIGITS[15 & data[i]];
}
return out;
}
}
package cn.luischen.utils;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
public class UUIDUtil {
private UUIDUtil() {
throw new IllegalStateException("Utility class");
}
public static String getUUID() {
return UUID.randomUUID().toString().replaceAll("-", "");
}
public static synchronized String getDateUUID() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
return sdf.format(new Date());
}
public static String getBrowserName(String agent) {
if (agent.indexOf("msie 7") > -1) {
return "ie7";
} else if (agent.indexOf("msie 8") > -1) {
return "ie8";
} else if (agent.indexOf("msie 9") > -1) {
return "ie9";
} else if (agent.indexOf("msie 10") > -1) {
return "ie10";
} else if (agent.indexOf("msie") > -1) {
return "ie";
} else if (agent.indexOf("opera") > -1) {
return "opera";
} else if (agent.indexOf("firefox") > -1) {
return "firefox";
} else if (agent.indexOf("webkit") > -1) {
return "webkit";
} else {
return agent.indexOf("gecko") > -1 && agent.indexOf("rv:11") > -1 ? "ie11" : "Others";
}
}
}