FileDownloadController.java 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package org.example.music.controller;
  2. import io.minio.GetObjectArgs;
  3. import io.minio.MinioClient;
  4. import io.minio.errors.*;
  5. import io.swagger.annotations.Api;
  6. import io.swagger.annotations.ApiOperation;
  7. import org.springframework.beans.factory.annotation.Autowired;
  8. import org.springframework.beans.factory.annotation.Value;
  9. import org.springframework.core.io.ByteArrayResource;
  10. import org.springframework.core.io.Resource;
  11. import org.springframework.http.HttpHeaders;
  12. import org.springframework.http.MediaType;
  13. import org.springframework.http.ResponseEntity;
  14. import org.springframework.stereotype.Controller;
  15. import org.springframework.web.bind.annotation.GetMapping;
  16. import org.springframework.web.bind.annotation.PathVariable;
  17. import org.springframework.web.bind.annotation.RequestMapping;
  18. import javax.servlet.http.HttpServletRequest;
  19. import java.io.ByteArrayOutputStream;
  20. import java.io.IOException;
  21. import java.io.InputStream;
  22. import java.security.InvalidKeyException;
  23. import java.security.NoSuchAlgorithmException;
  24. @Api(value = "FileDownloadController", tags = {"下载控制类"})
  25. @Controller
  26. @RequestMapping("/download")
  27. public class FileDownloadController {
  28. @Autowired
  29. private MinioClient minioClient;
  30. @Value("${minio.bucket-name}")
  31. private String bucketName;
  32. @ApiOperation(value = "下载")
  33. @GetMapping("/{fileName}")
  34. public ResponseEntity<Resource> downloadFile(@PathVariable String fileName, HttpServletRequest request) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
  35. GetObjectArgs args = GetObjectArgs.builder()
  36. .bucket(bucketName)
  37. .object(fileName)
  38. .build();
  39. InputStream inputStream = minioClient.getObject(args);
  40. ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
  41. byte[] buffer = new byte[1024];
  42. int bytesRead;
  43. while ((bytesRead = inputStream.read(buffer)) != -1) {
  44. outputStream.write(buffer, 0, bytesRead);
  45. }
  46. byte[] musicBytes = outputStream.toByteArray();
  47. // 创建一个ByteArrayResource对象,用于包装字节数组
  48. ByteArrayResource resource = new ByteArrayResource(musicBytes);
  49. // 构建响应头
  50. HttpHeaders headers = new HttpHeaders();
  51. headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + fileName);
  52. // 返回一个 ResponseEntity 对象
  53. return ResponseEntity.ok()
  54. .headers(headers)
  55. .contentLength(musicBytes.length)
  56. .contentType(MediaType.APPLICATION_OCTET_STREAM)
  57. .body(resource);
  58. }
  59. }