springboot實現mongodb上傳下載

一、上傳:java

private static Logger log = LoggerFactory.getLogger(MongoDbFSUtil.class);

private static final class MongoInstance {
public final static MongoClient client;
static {
client = new MongoClient("localhost", 27017);
}
}

public static MongoDatabase getDatabase(String databaseName) {
return MongoInstance.client.getDatabase(databaseName);
}

/**
* 上傳文件
* @param file
* @param databaseName
* @return
*/
public static String uploadFileToGridFS(File file,String databaseName) {
InputStream in = null;
String returnId = null;
String pathName = file.getPath();
String[] pathNameArray = pathName.split("\\\\");
String[] name = pathNameArray[pathNameArray.length-1].split("\\.");
String filename = name[0];
String type = name[name.length-1];
try {
in = new FileInputStream(file);
GridFSBucket bucket = GridFSBuckets.create(getDatabase(databaseName));
GridFSUploadOptions options = new GridFSUploadOptions();
//設置除filename覺得的其餘信息
Document metadata = new Document();
metadata.append("contentType", type);
options.metadata(metadata);
// ObjectId fileId = bucket.uploadFromStream(filename+type, in,options);
ObjectId fileId = bucket.uploadFromStream("123456", in,options);
returnId = fileId.toHexString();
log.info("文件上傳成功");
} catch (IOException e) {
log.info("upload fail:" + e);
} finally {
try {
in.close();
} catch (IOException e) {
log.info("close inputstream fail:" + e);
}
}
return returnId;
}
另一種上傳:使用
  1. @Autowired
  2.  
    private GridFsTemplate gridFsTemplate;

UserAO user = (UserAO) SecurityUtils.getSubject().getPrincipal();
Part part = request.getPart("file");
// 得到提交的文件名
String fileName = part.getSubmittedFileName();
// 得到文件輸入流
InputStream ins = part.getInputStream();
// 得到文件類型
String contentType = part.getContentType();
// 將文件存儲到mongodb中,mongodb 將會返回這個文件的具體信息
GridFSFile gridFSFile = gridFsTemplate.store(ins, fileName, contentType);
FileInfoAO fileInfo = new FileInfoAO();
fileInfo.setContentType(contentType);
fileInfo.setFileName(fileName);
fileInfo.setLastUpdateBy(user != null ? user.getId() : null);
fileInfo.setMongoFileId(gridFSFile.getId().toString());
return ServiceResultHelper.genResultWithSuccess(fileInfo);mongodb


二、下載
@RequestMapping("/downLoadFile")public void downLoadFile(String fileId, HttpServletRequest request, HttpServletResponse response)throws Exception{    Query query = Query.query(Criteria.where("filename").is("123456"));    // 查詢單個文件    GridFSDBFile gfsfile = gridFsTemplate.findOne(query);    if (gfsfile == null) {        return;    }    String fileName = gfsfile.getFilename().replace(",", "");    //處理中文文件名亂碼    if (request.getHeader("User-Agent").toUpperCase().contains("MSIE") ||            request.getHeader("User-Agent").toUpperCase().contains("TRIDENT")            || request.getHeader("User-Agent").toUpperCase().contains("EDGE")) {        fileName = java.net.URLEncoder.encode(fileName, "UTF-8");    } else {        //非IE瀏覽器的處理:        fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");    }    // 通知瀏覽器進行文件下載    response.setContentType(gfsfile.getContentType());    response.setHeader("Content-Disposition", "attachment;filename=\"" + "222.png" + "\"");    gfsfile.writeTo(response.getOutputStream());}
相關文章
相關標籤/搜索