Springmvc与Mongo GridFs 实现文件的上传和获取
Springmvc与Mongo GridFs 实现文件的上传和获取 ,最常见的情景莫过于手机客户端实现头像上传
上传文件,代码片段一:
@RequestMapping(method = RequestMethod.POST)
@ResponseBody
public Object uploadFile(HttpServletRequest request) {
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
request.getSession().getServletContext());
// 先判断request中是否包涵multipart类型的数据,
String fileUrl = "";
if (multipartResolver.isMultipart(request)) {
// 再将request中的数据转化成multipart类型的数据
MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
Iterator iter = multiRequest.getFileNames();
while (iter.hasNext()) {
MultipartFile file = multiRequest.getFile((String) iter.next());
if (file != null) {
try {
GridFSInputFile inputFile = fileService.save(file.getInputStream(), file.getOriginalFilename());
if (inputFile == null) {
return StatusConfig.FileUploadError;
} else {
fileUrl = inputFile.getId().toString();
}
} catch (IllegalStateException | IOException e) {}
}
}
HashMap hashMap = new HashMap();
fileUrl = this.getHttpFilePath() + fileUrl;
hashMap.put(ConstantsKey.STATUS, 200);
hashMap.put(ConstantsKey.DATA, fileUrl);
String json = ConvertUtils.as().toJson(hashMap);
System.out.println("photourl:" + json);
return json;
} else {}
}
上传文件,代码片段二:
@Autowired
private MongoDbFactory mongodbfactory;
/**
* 用给出的id,保存文件,透明处理已存在的情况
* id 可以是string,long,int,org.bson.types.ObjectId 类型
* @param in
* @param id
*/
public GridFSInputFile save(InputStream in, Object id){
GridFS gridFS = new GridFS(mongodbfactory.getDb());
GridFSInputFile gridFSInputFile = gridFS.createFile(in);
gridFSInputFile.save();
return gridFSInputFile;
}
通过Http请求文件
@RequestMapping(value = "https://www.it610.com/{id}", method = RequestMethod.GET)
public void getFile(@PathVariable String id, HttpServletResponse response) {
GridFSDBFile file = fileService.getById(new ObjectId(id));
OutputStream os = null;
try {
os = response.getOutputStream();
os.write(FileUtils.readInputStream(file.getInputStream()));
os.flush();
} catch (Exception e) {
e.printStackTrace();
} }
请求文件代码片段2:
/**
* 据id返回文件
*/
public GridFSDBFile getById(Object id){
DBObject query= new BasicDBObject("_id", id);
GridFS gridFS = new GridFS(mongodbfactory.getDb());
GridFSDBFile gridFSDBFile = gridFS.findOne(query);
return gridFSDBFile;
}
【Springmvc与Mongo GridFs 实现文件的上传和获取】
推荐阅读
- JAVA(抽象类与接口的区别&重载与重写&内存泄漏)
- Docker应用:容器间通信与Mariadb数据库主从复制
- 《真与假的困惑》???|《真与假的困惑》??? ——致良知是一种伟大的力量
- 第326天
- Shell-Bash变量与运算符
- MongoDB,Wondows下免安装版|MongoDB,Wondows下免安装版 (简化版操作)
- 逻辑回归的理解与python示例
- Guava|Guava RateLimiter与限流算法
- MAC安装Mongo
- 我和你之前距离