springboot+vue实现阿里云oss上传的示例代码
作者:左边的天堂
文件上传是常用的功能,本文主要介绍了springboot+vue实现阿里云oss上传的示例代码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
一、前言
我们后端开发中,时常需要用到文件上传的功能,无非是保存到服务器本地或者如阿里云、七牛云这种云存储的方案。本篇介绍一种使用后台springboot结合前端vue实现阿里云oss上传的功能。
如果想了解大文件直传oss的话,可移步到这一篇《使用springboot+vue实现阿里云oss文件直传,解决大文件分片上传问题》
二、前端实现过程
前端实现一个通用的上传组件UploadFile
<template> <div class="upload-file"> <el-upload :multiple="multiple" :accept="accept.join(',')" :action="uploadFileUrl" :before-upload="handleBeforeUpload" :file-list="fileList" :limit="limit" :on-error="handleUploadError" :on-exceed="handleExceed" :on-success="handleUploadSuccess" :show-file-list="false" :data="data" :headers="headers" class="upload-file-uploader" ref="fileUpload" > <!-- 上传按钮 --> <el-button size="mini" type="primary">选取文件</el-button> <template v-if="multiple"> (按住Ctrl键多选)</template> <!-- 上传提示 --> <div class="el-upload__tip" slot="tip" v-if="showTip && fileList.length<=0"> 请上传 <template v-if="limit"> 最多 <b style="color: #f56c6c">{{ limit }}个</b></template> <template v-if="fileSize"> 大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b></template> <template v-if="fileType"> 格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b></template> 的文件 </div> </el-upload> <!-- 文件列表 --> <transition-group class="upload-file-list el-upload-list el-upload-list--text" name="el-fade-in-linear" tag="ul" height="485"> <li v-for="(file, index) in fileList" :key="file.uid || index " class="el-upload-list__item ele-upload-list__item-content"> <el-link :href="file.url" rel="external nofollow" :underline="false" target="_blank"> <span class="el-icon-document"> {{ file.name }} </span> </el-link> <div class="ele-upload-list__item-content-action"> <el-link :underline="false" @click="handleDelete(index)" type="danger" style="width: 50px">删除</el-link> </div> </li> </transition-group> </div> </template> <script> import {getToken} from "@/utils/auth"; export default { name: "FileUpload", props: { // 是否可多选 multiple: { type: Boolean, default: true, }, // 值 value: [String, Object, Array], // 数量限制 limit: { type: Number, default: 5, }, // 大小限制(MB) fileSize: { type: Number, default: 5, }, // 文件类型, 例如['png', 'jpg', 'jpeg'] fileType: { type: Array, default: () => ["doc", "xls", "xlsx", "ppt", "txt", "pdf"], }, accept: { type: Array, default: () => [".doc", ".xls", ".xlsx", ".ppt", ".txt", ".pdf"], }, // 是否显示提示 isShowTip: { type: Boolean, default: true }, // 是否重命名 rename: { type: Boolean, default: false } }, data() { return { number: 0, uploadList: [], uploadFileUrl: process.env.VUE_APP_BASE_API + "/file/upload", // 上传文件服务器地址 headers: { Authorization: "Bearer " + getToken(), }, fileList: [], data: {} }; }, watch: { value: { handler(val) { if (val) { let temp = 1; // 首先将值转为数组 const list = Array.isArray(val) ? val : this.value.split(','); // 然后将数组转为对象数组 this.fileList = list.map(item => { if (typeof item === "string") { item = {name: item.name, url: item.url}; } item.uid = item.uid || new Date().getTime() + temp++; return item; }); } else { this.fileList = []; return []; } }, deep: true, immediate: true }, rename: { handler(val) { this.data = {rename: val} console.info(this.data) }, deep: true, immediate: true } }, computed: { // 是否显示提示 showTip() { return this.isShowTip && (this.fileType || this.fileSize); }, }, methods: { // 上传前校检格式和大小 handleBeforeUpload(file) { // 校检文件类型 if (this.fileType) { const fileName = file.name.split('.'); const fileExt = fileName[fileName.length - 1]; const isTypeOk = this.fileType.indexOf(fileExt) >= 0; if (!isTypeOk) { this.$modal.msgError(`文件格式不正确, 请上传${this.fileType.join("/")}格式文件!`); return false; } } // 校检文件大小 if (this.fileSize) { const isLt = file.size / 1024 / 1024 < this.fileSize; if (!isLt) { this.$modal.msgError(`上传文件大小不能超过 ${this.fileSize} MB!`); return false; } } this.$modal.loading("正在上传文件,请稍候..."); this.number++; return true; }, // 文件个数超出 handleExceed() { this.$modal.msgError(`上传文件数量不能超过 ${this.limit} 个!`); }, // 上传失败 handleUploadError(err) { this.$modal.msgError("上传文件失败,请重试"); this.$modal.closeLoading() }, // 上传成功回调 handleUploadSuccess(res, file) { if (res.code === 200) { this.uploadList.push({name: res.data.name, url: res.data.url}); this.uploadedSuccessfully(); } else { this.number--; this.$modal.closeLoading(); this.$modal.msgError(res.msg); this.$refs.fileUpload.handleRemove(file); this.uploadedSuccessfully(); } }, // 删除文件 handleDelete(index) { this.fileList.splice(index, 1); this.$emit("input", this.listToString(this.fileList)); }, // 上传结束处理 uploadedSuccessfully() { if (this.number > 0 && this.uploadList.length === this.number) { this.fileList = this.fileList.concat(this.uploadList); this.uploadList = []; this.number = 0; this.$emit("input", this.listToString(this.fileList)); this.$modal.closeLoading(); } }, // 获取文件名称 getFileName(name) { if (name.lastIndexOf("/") > -1) { return name.slice(name.lastIndexOf("/") + 1); } else { return ""; } }, // 对象转成指定字符串分隔 listToString(list, separator) { let strs = ""; separator = separator || ","; for (let i in list) { strs += list[i].url + separator; } return strs != '' ? strs.substr(0, strs.length - 1) : ''; } } }; </script> <style scoped lang="scss"> .upload-file-uploader { margin-bottom: 5px; } .upload-file-list { max-height: 420px; overflow-y: auto; } .upload-file-list .el-upload-list__item { border: 1px solid #e4e7ed; line-height: 2; margin-bottom: 10px; position: relative; } .upload-file-list .ele-upload-list__item-content { display: flex; justify-content: space-between; align-items: center; color: inherit; } .ele-upload-list__item-content-action .el-link { margin-right: 10px; } </style>
使用示例
<template> <div class="app-container"> <el-dialog title="附件上传" :visible.sync="open" width="700px" append-to-body> <el-form ref="form" :model="form" :rules="rules" label-width="100px"> <el-form-item label="重命名附件" prop="rename"> <el-radio-group v-model="form.rename"> <el-radio :label="false">否</el-radio> <el-radio :label="true">是</el-radio> </el-radio-group> </el-form-item> <el-form-item label="上传附件" prop="file" class="is-required"> <!-- 文件大小最多20M,数量最多20个 --> <file-upload ref="upload" :fileType="fileType" :accept="accept" :fileSize="20" :limit="20" :value="form.files" :rename="form.rename"/> </el-form-item> </el-form> <div slot="footer" class="dialog-footer"> <el-button type="primary" @click="submitForm">确 定</el-button> <el-button @click="cancel">取 消</el-button> </div> </el-dialog> </div> </template> <script> import { add } from "@/api/xxx"; // 请求后台的接口封装 import FileUpload from "@/components/FileUpload"; export default { name: "demo", components: { FileUpload }, data() { return { // 自定义允许上传的文件格式,也可以使用组件里面定义的默认格式 fileType: ['png','jpg','jpeg','gif'], accept: ['.png','.jpg','.jpeg','.gif'], // 表单参数 form: { // 是否重命名 rename: false, files: [] }, // 表单校验 rules: { files: [{type: 'array', required: true, message: "附件不能为空", trigger: "blur"}] } } }, methods: { /** 提交按钮 */ submitForm: function () { this.$refs["form"].validate(valid => { if (valid) { this.form.files = this.$refs.upload.fileList if (!Array.isArray(this.form.files) || this.form.files.length <= 0) { this.$alert("请上传附件"); return false; } console.info(this.form) add(this.form).then(() => { this.$modal.msgSuccess("操作成功"); this.open = false; }); } }); }, ... } } </script>
效果如下
文件选中后会立即上传,上传之后的效果如下
上传完后,后端返回的文件url可以跟其他表单字段一起保存到数据库。
三、后端实现过程
springboot后端实现逻辑
/** * 文件上传请求 */ @PostMapping("/upload") public Result upload(MultipartFile file, @RequestParam(required = false) Boolean rename) { try { SysFile sysFile = ossService.upload(file, rename); return Result.success(sysFile); } catch (Exception e) { log.error("上传文件失败", e); return Result.fail(e.getMessage()); } }
/** * 文件上传请求 */ @Override public SysFile upload(MultipartFile file, Boolean rename) throws IOException { // 获取文件名 String fileName = file.getOriginalFilename(); if (rename != null && rename) { // 重命名 Long fileFlag = new SnowFlakeGenerator().nextId(); fileName = fileFlag + "." + FileTypeUtils.getExtension(file); } String uri = String.format("file/%s", fileName); // 上传到文件服务 byte[] bytes = file.getBytes(); // 上传并返回访问地址 if (!this.upload(uri, bytes)) { throw new ServerErrorException("上传失败"); } String filePath = String.format("%s/%s", "阿里云OSS地址", uri); SysFile sysFile = new SysFile(); sysFile.setName(fileName); sysFile.setUrl(filePath); return sysFile; } private Boolean upload(String fileId, byte[] bytes) { InputStream in = null; try { in = new ByteArrayInputStream(bytes); return this.upload(fileId, in); } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } } } private Boolean upload(String key, InputStream in) { OSSClient client = getOSSClient(); try { ObjectMetadata objectMetadata = null; //文本文件特殊处理 if (key.endsWith(".txt")) { objectMetadata = new ObjectMetadata(); // 设置content type objectMetadata.setContentType("txt/plain;charset=utf-8"); } PutObjectResult result = client.putObject(config.getBucketName(), key, in, objectMetadata); ResponseMessage response = result.getResponse(); log.info("Oss upload result:{}", response.isSuccessful()); return response.isSuccessful(); } catch (OSSException oe) { log.error(oe.getErrorMessage()); return false; } catch (ClientException ce) { log.error(ce.getErrorMessage()); return false; } finally { client.shutdown(); } } private OSSClient getOSSClient() { // config--阿里云oss的配置信息,略 return (OSSClient) new OSSClientBuilder().build(config.getEndPoint(), config.getKeyId(), config.getSecret()); }
pom.xml
<!-- Aliyun oss --> <dependency> <groupId>com.aliyun.oss</groupId> <artifactId>aliyun-sdk-oss</artifactId> <version>3.10.2</version> </dependency>
到此这篇关于springboot+vue实现阿里云oss上传的示例代码的文章就介绍到这了,更多相关springboot vue 阿里云oss上传内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!