上传文件
Controller@ApiOperation(value = "上传文件", tags = {"通用接口",})
@ApiResponses(value = {@ApiResponse(code = 200, message = "上传文件", response = ResultVO.class)})
@PostMapping("/upload/file")
public ResultVO uploadFile(@ApiParam(value = "文件") @RequestParam("file") MultipartFile file,@ApiParam(value = "id") @RequestParam("id")Integer id) {String filePath = "xx/"+file.getOriginalFilename();ResultVO resultVO = new ResultVO();resultVO.setCode(200);resultVO.setMessage("上传成功");try {ossUtil.uploadFile(file.getInputStream(),filePath);}catch (Exception e){resultVO.setMessage("上传失败");e.printStackTrace();}return resultVO;
}
Service/*** 上传文件* @param inputStream* @param fileName*/public void uploadFile(InputStream inputStream, String fileName){OSS ossClient = new OSSClientBuilder().build(endpoint, keyId, keySecret);String objectName = fileDir+"/"+fileName;if(!ossClient.doesBucketExist(bucketName)){ossClient.createBucket(bucketName);}ossClient.putObject(bucketName,objectName,inputStream);ossClient.shutdown();}
下载文件
Controller/*** 上传文件
*/
@ApiOperation(value = "下载文件", tags = {"通用接口",})
@ApiResponses(value = {@ApiResponse(code = 200, message = "下载文件", response = ResultVO.class)})
@GetMapping("/down/file")
public ResponseEntity downFile(@ApiParam(value = "文件名,包括后缀") @RequestParam("name") String name) {ResultVO resultVO = new ResultVO();String filePath = "xx/"+name;resultVO.setCode(200);resultVO.setMessage("下载成功");try {
// ossUtil.downloadFile(name,saveDir,filePath);InputStream inputStream = ossUtil.downloadFile(filePath);HttpHeaders headers = new HttpHeaders();headers.add("Cache-Control", "no-cache, no-store, must-revalidate");headers.add("Content-Disposition", "attachment; filename=" + new String(name.getBytes("UTF-8"),"iso-8859-1"));headers.add("Pragma", "no-cache");headers.add("Expires", "0");headers.add("Last-Modified", new Date().toString());headers.add("ETag", String.valueOf(System.currentTimeMillis()));return new ResponseEntity<byte[]>(ossUtil.getBytes(inputStream), headers, HttpStatus.OK);}catch (Exception e){resultVO.setMessage("下载失败");e.printStackTrace();}return ResponseEntity.notFound().build();
}
Service/*** 下载文件*/public InputStream downloadFile(String filePath) throws IOException {OSS ossClient = new OSSClientBuilder().build(endpoint, keyId, keySecret);String objectName = fileDir+"/"+filePath;OSSObject ossObject = ossClient.getObject(bucketName, objectName);
// ossClient.shutdown();return ossObject.getObjectContent();}