|
@ -15,8 +15,10 @@ import org.springframework.beans.factory.annotation.Autowired;
|
|
|
import org.springframework.data.mongodb.core.query.Query;
|
|
|
import org.springframework.data.mongodb.gridfs.GridFsCriteria;
|
|
|
import org.springframework.data.mongodb.gridfs.GridFsOperations;
|
|
|
import org.springframework.stereotype.Component;
|
|
|
import org.springframework.web.multipart.commons.CommonsMultipartFile;
|
|
|
|
|
|
import javax.annotation.PostConstruct;
|
|
|
import java.io.*;
|
|
|
import java.sql.Blob;
|
|
|
import java.util.*;
|
|
@ -28,13 +30,22 @@ import java.util.*;
|
|
|
* @vsrsion 1.0
|
|
|
* Created at 2016/7/21.
|
|
|
*/
|
|
|
@Component
|
|
|
public class GridFSUtil {
|
|
|
|
|
|
public static final int defaultChunkSize = 1024 * 1024 * 4;
|
|
|
|
|
|
@Autowired
|
|
|
private GridFsOperations operations;
|
|
|
|
|
|
private static GridFsOperations gridFsOperations;
|
|
|
|
|
|
|
|
|
@PostConstruct
|
|
|
public void init() {
|
|
|
gridFsOperations = this.operations;
|
|
|
}
|
|
|
|
|
|
public static ObjectId uploadFile(String dbName, Blob blob, String fileType, Map<String, Object> params) {
|
|
|
// String fileName = UUID.randomUUID().toString() + "." + fileType;
|
|
|
//自定义字段
|
|
@ -348,6 +359,25 @@ public class GridFSUtil {
|
|
|
GridFSUploadOptions gridFSUploadOptions = new GridFSUploadOptions()
|
|
|
.chunkSizeBytes(defaultChunkSize).metadata(metaDocument);
|
|
|
FileInputStream fileInputStream = null;
|
|
|
|
|
|
// Create some custom options
|
|
|
// GridFSUploadOptions gridFSUploadOptions = new GridFSUploadOptions()
|
|
|
// .chunkSizeBytes(defaultChunkSize).metadata(metaDocument);
|
|
|
// String fileName = UUID.randomUUID() + file.getFileItem().getName();
|
|
|
// GridFSUploadStream uploadStream = gridFS.openUploadStream(fileName, gridFSUploadOptions);
|
|
|
// try {
|
|
|
// byte[] data = FileUtil.toByteArray(filePath);
|
|
|
// uploadStream.write(data);
|
|
|
// ObjectId id = uploadStream.getFileId();
|
|
|
// if (id != null) {
|
|
|
// return fileName;
|
|
|
// }
|
|
|
// } finally {
|
|
|
// if (uploadStream != null) {
|
|
|
// uploadStream.close();
|
|
|
// }
|
|
|
// }
|
|
|
|
|
|
try {
|
|
|
fileInputStream = new FileInputStream(filePath);
|
|
|
com.mongodb.gridfs.GridFSFile gridFSFile = gridFsOperations.store(fileInputStream, gridFSUploadOptions);
|
|
@ -397,7 +427,7 @@ public class GridFSUtil {
|
|
|
public static String readFile(String dbName, String fileName) {
|
|
|
try {
|
|
|
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
|
|
|
GridFSDBFile gridFSDBFile = gridFsOperations.findOne(Query.query(GridFsCriteria.where("").is(fileName)));
|
|
|
GridFSDBFile gridFSDBFile = gridFsOperations.findOne(Query.query(GridFsCriteria.where("filename").is(fileName)));
|
|
|
gridFSDBFile.writeTo(byteArrayOutputStream);
|
|
|
return byteArrayOutputStream.toString();
|
|
|
} catch (Exception e) {
|