拿来即用:SpringBoot+Minio+vue-uploader实现分片上传
以下是一个简化的Spring Boot和MinIO结合使用进行分片上传的例子。
Spring Boot 控制器 (UploadController.java):
import io.minio.MinioClient;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
@RestController
public class UploadController {
private final MinioClient minioClient;
public UploadController(MinioClient minioClient) {
this.minioClient = minioClient;
}
@PostMapping("/upload")
public String uploadFile(@RequestParam("file") MultipartFile file) {
try {
minioClient.putObject("my-bucket", file.getOriginalFilename(), file.getInputStream(), file.getContentType());
return "File uploaded successfully";
} catch (Exception e) {
e.printStackTrace();
return "Failed to upload file";
}
}
}
MinIO 客户端配置 (MinioConfig.java):
import io.minio.MinioClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MinioConfig {
@Bean
public MinioClient minioClient() {
try {
return MinioClient.builder()
.endpoint("http://127.0.0.1:9000")
.credentials("minioadmin", "minioadmin")
.build();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("Error while creating MinioClient", e);
}
}
}
前端 Vue.js 使用 vue-upload-component 实现分片上传:
<template>
<file-upload
ref="upload"
v-model="files"
:post-action="postAction"
:put-action="putAction"
:put-headers="putHeaders"
></file-upload>
</template>
<script>
import FileUpload from 'vue-upload-component'
export default {
components: {
FileUpload
},
data() {
return {
files: [],
postAction: '/upload',
putAction: 'http://127.0.0.1:9000/my-bucket',
putHeaders: {
Authorization: 'Bearer ' + this.getToken()
}
}
},
methods: {
getToken() {
// 获取MinIO的Token或者通过其他方式进行认证
return 'your-minio-token';
}
}
}
</script>
确保你已经在项目中包含了MinIO的依赖和相关配置,并且MinIO服务器正在运行。这个例子假设你已经有了一个运行中的Spring Boot应用和一个MinIO服务器。
注意: 实际应用中你需要对上传的文件进行验证和权限控制,并处理可能出现的异常。这里为了简化,直接将其省略。
评论已关闭