vue+minio实现文件上传操作

vue+minio实现文件上传操作

minio文件上传

minio文件上传有两种方法:

  1. 第一种是通过ak,sk,调用minio的sdk putObject进行文件上传;该方法支持go,java,js等各种语言,
  2. 第二种是后端生成presignedUrl,前端通过该url实现文件上传;

vue+minio实现文件上传操作

以上说的两种方法中,第一种方法会把ak,sk暴露给前端,造成一定的安全隐患;所以如果要使用第一种方法,需要向后端请求生成临时的ak,sk;

这边我们实现了第二种方法。

前端代码如下,这种方法的思路是先向后端请求生成presigned-url,然后再通过binary的方式进行文件上传;注意这里有一个小坑,就是上传文件不要使用form-data,否则会在文件加上WebKitFormBoundary前缀,minio生成的presigned-url没有对此进行解析,这种上传方式会导致如.png .mp4的文件打不开。

<template>
    <el-upload ref="uploadRef" :http-request="uploadSubmit" :auto-upload="false" v-model:file-list="fileList" :limit="1"
        :on-success="onSuccess">
        <template #trigger>
            <el-button type="primary" style="width: 100px;">select</el-button>
        </template>
        <el-button type="success" @click="uploadRef.submit()" style="margin-left: 2rem;width: 100px;">upload</el-button>
        <div class="demo-progress">
            <el-progress :percentage=percent />
        </div>
        <el-button size="small" type="primary" @click="cancelUpload">取消上传</el-button>
    </el-upload>
</template>

<script setup>
import { ref } from 'vue'
import axios from 'axios';
const uploadRef = ref();
const fileList = ref([]);
let percent = ref(0);
let Cancel = axios.CancelToken.source()

async function uploadSubmit(options) {
    console.log(options)
    const item = options['file'];

    var presignedUrl = ""
    var objSize = item.size;
    let bodyJson = {
        accessKey: 'ak',
        bucket: 'bucket',
        object: 'object',
        expireSeconds: 3600 // s
    };

    axios.put('/path/uploadUrl', bodyJson).then(res => {
        if (res.status == 200) {
            presignedUrl = res.data.data
            axios({
                method: "put",
                url: presignedUrl,
                data: item, // 重点1,直接将原始二进制流赋给data
                headers: {
                    "Content-Type": "application/octet-stream", // 重点2
                },
                timeout: 3600000, // ms
                onUploadProgress: function (e) {
                    percent.value = parseInt(e.loaded / objSize * 100);
                },
                cancelToken: Cancel.token
            }).then(res => {
                if (res.status == 200) {
                    console.log('success')
                }
            }).catch(
                err => {
                    console.log(err)
                }
            )   
        }
    })
}

const onSuccess = (response, file, fileList) => {
    console.log(response);
    console.log(file);
    console.log(fileList);
}

function cancelUpload() {
    Cancel.cancel();
    Cancel = axios.CancelToken.source(); // 重新定义cancelToken
}


</script>
<style scoped>
.demo-progress .el-progress--line {
    margin-bottom: 15px;
    width: 350px;
}
</style>
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
实现Spring Boot和Vue.jsMinIO秒传和断点续传,您可以遵循以下步骤: 1. 创建一个Spring Boot项目并添加MinIO依赖: ``` <dependency> <groupId>io.minio</groupId> <artifactId>minio</artifactId> <version>7.1.0</version> </dependency> ``` 2. 在您的Spring Boot应用程序中配置MinIO。您可以使用`MinioClient`类来进行这个操作。在配置文件中添加以下属性: ``` minio.accessKey=your-access-key minio.secretKey=your-secret-key minio.endpoint=your-minio-endpoint ``` 3. 在Vue.js中,您可以使用`axios`库来上传文件。以下是上传文件的示例代码: ``` <template> <div> <input type="file" v-on:change="uploadFile" /> </div> </template> <script> import axios from 'axios'; export default { methods: { async uploadFile(event) { const file = event.target.files[0]; const url = 'http://localhost:8080/uploadFile'; const data = new FormData(); data.append('file', file); try { const response = await axios.post(url, data, { headers: { 'Content-Type': 'multipart/form-data', }, }); console.log(response.data); } catch (error) { console.log(error); } }, }, }; </script> ``` 4. 在Spring Boot中,您可以创建一个REST API端点来处理文件上传请求。以下是一个示例代码: ``` @RestController public class FileUploadController { @Autowired private MinioClient minioClient; @PostMapping("/uploadFile") public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) throws Exception { String fileName = file.getOriginalFilename(); InputStream inputStream = file.getInputStream(); ObjectMetadata metadata = new ObjectMetadata(); metadata.setContentType(file.getContentType()); metadata.setContentLength(file.getSize()); PutObjectOptions options = new PutObjectOptions(metadata); minioClient.putObject("my-bucket", fileName, inputStream, options); return ResponseEntity.ok("File uploaded successfully!"); } } ``` 5. 要实现MinIO的断点续传,您可以使用MinIO Java客户端库中提供的`MultiFileUploader`类。以下是一个示例代码: ``` @RestController public class FileUploadController { @Autowired private MinioClient minioClient; @PostMapping("/uploadFile") public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) throws Exception { String fileName = file.getOriginalFilename(); InputStream inputStream = file.getInputStream(); ObjectMetadata metadata = new ObjectMetadata(); metadata.setContentType(file.getContentType()); metadata.setContentLength(file.getSize()); PutObjectOptions options = new PutObjectOptions(metadata); MultiFileUploader uploader = new MultiFileUploader(minioClient, "my-bucket", fileName); uploader.setPartSize(5 * 1024 * 1024); // 5MB uploader.upload(inputStream, options); return ResponseEntity.ok("File uploaded successfully!"); } } ``` 以上是Spring Boot和Vue.jsMinIO秒传和断点续传的基本实现。您可以根据自己的需求进行修改和扩展。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值