[Java] 纯文本查看 复制代码
@RestController
@RequestMapping("/api")
public class GridFSApi {
private static Logger LOGGER = Logger.getLogger(GridFSApi.class);
@Autowired
private GridFsTemplate gridFsTemplate;
@RequestMapping(value = "/save", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public Response save(@RequestParam(value = "file", required = true) MultipartFile file) {
LOGGER.info("Saving file..");
DBObject metaData = new BasicDBObject();
metaData.put("createdDate", new Date());
String fileName = UUID.randomUUID().toString();
LOGGER.info("File Name: " + fileName);
InputStream inputStream = null;
try {
inputStream = file.getInputStream();
gridFsTemplate.store(inputStream, fileName, "image", metaData);
LOGGER.info("File saved: " + fileName);
} catch (IOException e) {
LOGGER.error("IOException: " + e);
throw new RuntimeException("System Exception while handling request");
}
LOGGER.info("File return: " + fileName);
return new Response(fileName);
}
@RequestMapping(value = "/get", method = RequestMethod.GET, produces = MediaType.IMAGE_JPEG_VALUE)
public byte[] get(@RequestParam(value = "fileName", required = true) String fileName) throws IOException {
LOGGER.info("Getting file.." + fileName);
List<GridFSDBFile> result = gridFsTemplate
.find(new Query().addCriteria(Criteria.where("filename").is(fileName)));
if (result == null || result.size() == 0) {
LOGGER.info("File not found" + fileName);
throw new RuntimeException("No file with name: " + fileName);
}
LOGGER.info("File found " + fileName);
return IOUtils.toByteArray(result.get(0).getInputStream());
}
@RequestMapping(value = "/delete", method = RequestMethod.DELETE)
public void delete(@RequestParam(value = "fileName", required = true) String fileName) {
LOGGER.info("Deleting file.." + fileName);
gridFsTemplate.delete(new Query().addCriteria(Criteria.where("filename").is(fileName)));
LOGGER.info("File deleted " + fileName);
}
}