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<String> 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<String, Object> hashMap = new HashMap<String, Object>();
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 = "/{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;
}