Sping Boot MongoDb实现文件上传和下载
文件的上传
@PostMapping("/upload")@ApiOperation(value = "文件上传")public ExtResult<FileVo> upload(@Param("file") MultipartFile file, HttpServletRequest request) {
String code=request.getParameter("code");if(code==null){
code="default";}FileVo vo = uploadService.upload(file,code);return ExtResult.ok(vo);}
@Overridepublic FileVo upload(MultipartFile file, String code) {
checkFile(file);FileVo vo = new FileVo();String fileName = file.getOriginalFilename();String contentType = file.getContentType();String type = fileName.substring(fileName.lastIndexOf("."));try {
String filenameId = FileUtil.MultipartFileMD5(file);String mdFilename = filenameId+ fileName.substring(fileName.lastIndexOf("."));InputStream is = file.getInputStream();Query query = Query.query(Criteria.where("filename").is(mdFilename));GridFSFile gridFile = gridFsTemplate.findOne(query);ObjectId objectId ;if(gridFile!=null) {
objectId = gridFile.getObjectId();}else{
objectId = gridFsTemplate.store(is, mdFilename, contentType);}vo.setFilename(fileName);vo.setFileType(type);vo.setMongodbId(String.valueOf(objectId));} catch (Exception e) {
log.error("业务异常={}", e.getMessage(), e);throw new BusinessException(ErrorCodeEnum.SDK_FILE_UPLOAD_FAILURE);}return vo;}
@Data
@ApiModel(value = "文件上传响应类")
public class FileVo implements Serializable {
@ApiModelProperty(value = "Mongodb标识Id")private String mongodbId;@ApiModelProperty(value = "磁盘地址")private String fileUrl;@ApiModelProperty(value = "原文件名")private String filename;@ApiModelProperty(value = "文件后缀类型")private String fileType;}
文件的预览
@GetMapping(value = "/show")@ApiOperation(value = "预览图片")public ExtResult show(String mongoId, HttpServletResponse response)throws IOException {
uploadService.show(mongoId,response);return ExtResult.ok();}
@Autowiredprivate GridFsTemplate gridFsTemplate;@Autowiredprivate MongoDbFactory mongoDbFactory;@Overridepublic void show(String mongoId, HttpServletResponse response) throws IOException {
GridFSFile gridFSFile = this.getById(mongoId);if (gridFSFile != null) {
GridFSBucket bucket = GridFSBuckets.create(mongoDbFactory.getDb());GridFSDownloadStream gridFSDownloadStream = bucket.openDownloadStream(gridFSFile.getObjectId());GridFsResource gridFsResource = new GridFsResource(gridFSFile,gridFSDownloadStream);ClassPathResource classPathResource = new ClassPathResource(WATERMARK);ImageUtil.addWatermark(gridFsResource.getInputStream(),classPathResource.getFile(),response.getOutputStream(),0.5f);}else {
throw new BusinessException(ErrorCodeEnum.SDK_FILE_NOT_EXIT);}}
public GridFSFile getById(String mongoId){
Query query = Query.query(Criteria.where("_id").is(mongoId));GridFSFile gfsFile = gridFsTemplate.findOne(query);return gfsFile;}
@Overridepublic void showNoWater(String mongoId, HttpServletResponse response) throws IOException {
GridFSFile gridFSFile = this.getById(mongoId);if (gridFSFile != null) {
GridFSBucket bucket = GridFSBuckets.create(mongoDbFactory.getDb());GridFSDownloadStream gridFSDownloadStream = bucket.openDownloadStream(gridFSFile.getObjectId());GridFsResource gridFsResource = new GridFsResource(gridFSFile,gridFSDownloadStream);IOUtils.copy(gridFsResource.getInputStream(), response.getOutputStream());}else {
throw new BusinessException(ErrorCodeEnum.SDK_FILE_NOT_EXIT);}}
public void checkFile(MultipartFile multipartFile){
if (multipartFile==null) {
throw new BusinessException(ErrorCodeEnum.SDK_FILE_NOT_EXIT);}String name = multipartFile.getOriginalFilename();String documentType = name.substring(name.lastIndexOf("."));String fileLastType = documentType.toLowerCase();List<String> lastType = SdkConstant.UploadFile.FILE_MAP;if(!lastType.contains(fileLastType)) {
throw new BusinessException(ErrorCodeEnum.SDK_FILE_TYPE_INCORRECT);}if (multipartFile.getSize() > SdkConstant.UploadFile.MAX_UPLOAD_SIZE) {
throw new BusinessException(ErrorCodeEnum.SDK_FILE_BIG);}}
文件的下载
@GetMapping(value = "/download")@ApiOperation(value = "文件下载")public void downloadFile(String mongoId,HttpServletRequest request, HttpServletResponse response) throws IOException {
if(StrUtil.isNotBlank(mongoId)) {
uploadService.downFile(mongoId, request, response);}}
@Overridepublic void downFile(String mongoId, HttpServletRequest request, HttpServletResponse response)throws IOException{
GridFSFile gfsFile = this.getById(mongoId);if(gfsFile==null){
throw new BusinessException(ErrorCodeEnum.SDK_FILE_NOT_EXIST);}InputStream is = GridFSBuckets.create(mongoDbFactory.getDb()).openDownloadStream(gfsFile.getObjectId());GridFsResource gridFsResource=new GridFsResource(gfsFile,is);String fileName = gfsFile.getFilename().replace(",", "");this.fileDown(gridFsResource.getInputStream(),fileName,request,response);}
private void fileDown(InputStream inputStream,String fileName,HttpServletRequest request,HttpServletResponse response)throws IOException{
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 {
fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");}response.setHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");IOUtils.copy(inputStream,response.getOutputStream());}
private void fileWaterDown(InputStream inputStream,String fileName,HttpServletRequest request,HttpServletResponse response)throws IOException{
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 {
fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");}response.setHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");ClassPathResource classPathResource = new ClassPathResource(WATERMARK);ImageUtil.addWatermark(inputStream,classPathResource.getFile(),response.getOutputStream(),0.5f);}