Skip to content

Commit

Permalink
增加了minio,用来保存歌曲,并测试下载和播放功能成功
Browse files Browse the repository at this point in the history
增加了minio,用来保存歌曲,并测试下载和播放功能成功
  • Loading branch information
nanshaws committed Mar 14, 2024
1 parent cbc5889 commit 9ef06d2
Show file tree
Hide file tree
Showing 8 changed files with 221 additions and 25 deletions.
24 changes: 24 additions & 0 deletions music-server/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,30 @@
<artifactId>commons-pool2</artifactId>
<version>2.11.1</version>
</dependency>
<dependency>
<groupId>io.minio</groupId>
<artifactId>minio</artifactId>
<version>8.3.0</version>
</dependency>

<dependency>
<groupId>me.tongfei</groupId>
<artifactId>progressbar</artifactId>
<version>0.5.3</version>
</dependency>

<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.8.1</version>
</dependency>

<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.8.0</version> <!-- 或者是最新的版本 -->
</dependency>


</dependencies>

Expand Down
27 changes: 27 additions & 0 deletions music-server/src/main/java/com/example/yin/config/MinioConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package com.example.yin.config;

import io.minio.MinioClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MinioConfig {

@Value("${minio.endpoint}")
private String minioEndpoint;

@Value("${minio.access-key}")
private String minioAccessKey;

@Value("${minio.secret-key}")
private String minioSecretKey;

@Bean
public MinioClient minioClient() {
return MinioClient.builder()
.endpoint(minioEndpoint)
.credentials(minioAccessKey, minioSecretKey)
.build();
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
package com.example.yin.controller;

import io.minio.GetObjectArgs;
import io.minio.MinioClient;
import io.minio.errors.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
Expand All @@ -13,27 +18,44 @@
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

@Controller
@RequestMapping("/download")
public class FileDownloadController {

@Autowired
private MinioClient minioClient;
@Value("${minio.bucket-name}")
private String bucketName;

@GetMapping("/{fileName}")
public ResponseEntity<Resource> downloadFile(@PathVariable String fileName, HttpServletRequest request) {
// 加载文件作为资源
String filePath = System.getProperty("user.dir") + System.getProperty("file.separator") + "song\\"+fileName;
File file=new File(filePath);
public ResponseEntity<Resource> downloadFile(@PathVariable String fileName, HttpServletRequest request) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {

GetObjectArgs args = GetObjectArgs.builder()
.bucket(bucketName)
.object(fileName)
.build();
InputStream inputStream = minioClient.getObject(args);

byte[] musicBytes = getMusicBytesFromFileName(file);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
byte[] musicBytes = outputStream.toByteArray();
// 创建一个ByteArrayResource对象,用于包装字节数组
ByteArrayResource resource = new ByteArrayResource(musicBytes);
// 构建响应头
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + fileName);

// 返回一个 ResponseEntity 对象
return ResponseEntity.ok()
.headers(headers)
Expand All @@ -42,14 +64,4 @@ public ResponseEntity<Resource> downloadFile(@PathVariable String fileName, Http
.body(resource);
}

// 这个方法需要根据你的实际情况来获取音乐文件的字节数组
private byte[] getMusicBytesFromFileName(File file) {
try {
return Files.readAllBytes(file.toPath());
} catch (IOException e) {
e.printStackTrace();
// 如果发生异常,你可以返回一个空数组或者其他适当的错误处理
return new byte[0];
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package com.example.yin.controller;

import io.minio.GetObjectArgs;
import io.minio.MinioClient;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.client.RestTemplate;

import java.io.InputStream;


@Controller
public class MinioController {
@Value("${minio.bucket-name}")
private String bucketName;
@Autowired
private MinioClient minioClient;
@GetMapping("/user01/{fileName:.+}")
public ResponseEntity<byte[]> getMusic(@PathVariable String fileName) {
try {
GetObjectArgs args = GetObjectArgs.builder()
.bucket(bucketName)
.object(fileName)
.build();
InputStream inputStream = minioClient.getObject(args);

// 将文件内容读取为字节数组
byte[] bytes = IOUtils.toByteArray(inputStream);

// 设置响应头,指示浏览器如何处理响应内容
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
headers.setContentDispositionFormData("attachment", fileName); // 如果需要下载文件,可以使用此头部

// 返回字节数组作为响应
return new ResponseEntity<>(bytes, headers, HttpStatus.OK);
} catch (Exception e) {
e.printStackTrace();
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
package com.example.yin.controller;

import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.MinioException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Properties;

@Service
public class MinioUploadController {

private static MinioClient minioClient;
private static String bucketName;

public static void init(){
Properties properties = new Properties();
try {
// 使用类加载器获取资源文件的输入流
InputStream inputStream = MinioUploadController.class.getClassLoader().getResourceAsStream("application-dev.properties");
if (inputStream != null) {
properties.load(inputStream);
String minioEndpoint = properties.getProperty("minio.endpoint");
String minioAccessKey = properties.getProperty("minio.access-key");
String minioSecretKey = properties.getProperty("minio.secret-key");
String minioBucketName = properties.getProperty("minio.bucket-name");
bucketName = minioBucketName;
minioClient = MinioClient.builder()
.endpoint(minioEndpoint)
.credentials(minioAccessKey, minioSecretKey)
.build();
}
}catch (Exception e){
System.out.println(e);
}
}

public static String uploadFile(MultipartFile file) {
try {
init();
InputStream inputStream = file.getInputStream();
minioClient.putObject(
PutObjectArgs.builder()
.bucket(bucketName)
.object(file.getOriginalFilename())
.stream(inputStream, inputStream.available(), -1)
.contentType(file.getContentType())
.build()
);
return "File uploaded successfully!";
} catch (MinioException | IOException | NoSuchAlgorithmException | InvalidKeyException e) {
e.printStackTrace();
return "Error uploading file to MinIO: " + e.getMessage();
} catch (Exception e) {
throw new RuntimeException(e);
}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -92,4 +92,5 @@ public R updateSongPic(@RequestParam("file") MultipartFile urlFile, @RequestPara
public R updateSongUrl(@RequestParam("file") MultipartFile urlFile, @RequestParam("id") int id) {
return songService.updateSongUrl(urlFile, id);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,15 @@
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.yin.common.R;
import com.example.yin.controller.MinioUploadController;
import com.example.yin.mapper.SongMapper;
import com.example.yin.model.domain.Song;
import com.example.yin.model.request.SongRequest;
import com.example.yin.service.SongService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

Expand All @@ -28,6 +31,9 @@ public class SongServiceImpl extends ServiceImpl<SongMapper, Song> implements So
@Autowired
private SongMapper songMapper;

@Value("${minio.bucket-name}")
private String bucketName;

@Override
public R allSong() {
return R.success(null, songMapper.selectList(null));
Expand All @@ -40,14 +46,9 @@ public R addSong(SongRequest addSongRequest, MultipartFile lrcfile,MultipartFile
String pic = "/img/songPic/tubiao.jpg";
String fileName = mpfile.getOriginalFilename();
String filePath = System.getProperty("user.dir") + System.getProperty("file.separator") + "song";
File file1 = new File(filePath);
if (!file1.exists()) {
if (!file1.mkdir()) {
return R.fatal("创建文件失败");
}
}
String s = MinioUploadController.uploadFile(mpfile);
File dest = new File(filePath + System.getProperty("file.separator") + fileName);
String storeUrlPath = "/song/" + fileName;
String storeUrlPath = "/"+bucketName+"/" + fileName;
try {
mpfile.transferTo(dest);
} catch (IOException e) {
Expand All @@ -68,7 +69,7 @@ public R addSong(SongRequest addSongRequest, MultipartFile lrcfile,MultipartFile
throw new RuntimeException(e);
}
}
if (songMapper.insert(song) > 0) {
if (s.equals("File uploaded successfully!")&&songMapper.insert(song) > 0) {
return R.success("上传成功", storeUrlPath);
} else {
return R.error("上传失败");
Expand Down
10 changes: 10 additions & 0 deletions music-server/src/main/resources/application-dev.properties
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,13 @@ spring.datasource.url=jdbc:mysql://localhost:3306/tp_music?useSSL=false&allowPub
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

minio.endpoint=http://localhost:9000
minio.access-key=root
minio.secret-key=123456789
minio.bucket-name=user01
# ????????
spring.servlet.multipart.max-file-size= 50MB
# ????????????
spring.servlet.multipart.max-request-size= 50MB

0 comments on commit 9ef06d2

Please sign in to comment.