springboot+vue實(shí)現(xiàn)阿里云oss上傳的示例代碼
一、前言
我們后端開(kāi)發(fā)中,時(shí)常需要用到文件上傳的功能,無(wú)非是保存到服務(wù)器本地或者如阿里云、七牛云這種云存儲(chǔ)的方案。本篇介紹一種使用后臺(tái)springboot結(jié)合前端vue實(shí)現(xiàn)阿里云oss上傳的功能。
如果想了解大文件直傳oss的話,可移步到這一篇《使用springboot+vue實(shí)現(xiàn)阿里云oss文件直傳,解決大文件分片上傳問(wèn)題》
二、前端實(shí)現(xiàn)過(guò)程
前端實(shí)現(xiàn)一個(gè)通用的上傳組件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"> 請(qǐng)上傳 <template v-if="limit"> 最多 <b style="color: #f56c6c">{{ limit }}個(gè)</b></template> <template v-if="fileSize"> 大小不超過(guò) <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], // 數(shù)量限制 limit: { type: Number, default: 5, }, // 大小限制(MB) fileSize: { type: Number, default: 5, }, // 文件類(lèi)型, 例如['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", // 上傳文件服務(wù)器地址 headers: { Authorization: "Bearer " + getToken(), }, fileList: [], data: {} }; }, watch: { value: { handler(val) { if (val) { let temp = 1; // 首先將值轉(zhuǎn)為數(shù)組 const list = Array.isArray(val) ? val : this.value.split(','); // 然后將數(shù)組轉(zhuǎn)為對(duì)象數(shù)組 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) { // 校檢文件類(lèi)型 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(`文件格式不正確, 請(qǐng)上傳${this.fileType.join("/")}格式文件!`); return false; } } // 校檢文件大小 if (this.fileSize) { const isLt = file.size / 1024 / 1024 < this.fileSize; if (!isLt) { this.$modal.msgError(`上傳文件大小不能超過(guò) ${this.fileSize} MB!`); return false; } } this.$modal.loading("正在上傳文件,請(qǐng)稍候..."); this.number++; return true; }, // 文件個(gè)數(shù)超出 handleExceed() { this.$modal.msgError(`上傳文件數(shù)量不能超過(guò) ${this.limit} 個(gè)!`); }, // 上傳失敗 handleUploadError(err) { this.$modal.msgError("上傳文件失敗,請(qǐng)重試"); this.$modal.closeLoading() }, // 上傳成功回調(diào) 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)); }, // 上傳結(jié)束處理 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 ""; } }, // 對(duì)象轉(zhuǎn)成指定字符串分隔 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,數(shù)量最多20個(gè) --> <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"; // 請(qǐng)求后臺(tái)的接口封裝 import FileUpload from "@/components/FileUpload"; export default { name: "demo", components: { FileUpload }, data() { return { // 自定義允許上傳的文件格式,也可以使用組件里面定義的默認(rèn)格式 fileType: ['png','jpg','jpeg','gif'], accept: ['.png','.jpg','.jpeg','.gif'], // 表單參數(shù) form: { // 是否重命名 rename: false, files: [] }, // 表單校驗(yàn) 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("請(qǐng)上傳附件"); return false; } console.info(this.form) add(this.form).then(() => { this.$modal.msgSuccess("操作成功"); this.open = false; }); } }); }, ... } } </script>
效果如下
文件選中后會(huì)立即上傳,上傳之后的效果如下
上傳完后,后端返回的文件url可以跟其他表單字段一起保存到數(shù)據(jù)庫(kù)。
三、后端實(shí)現(xiàn)過(guò)程
springboot后端實(shí)現(xiàn)邏輯
/** * 文件上傳請(qǐng)求 */ @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()); } }
/** * 文件上傳請(qǐng)求 */ @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); // 上傳到文件服務(wù) byte[] bytes = file.getBytes(); // 上傳并返回訪問(wèn)地址 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(); // 設(shè)置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>
到此這篇關(guān)于springboot+vue實(shí)現(xiàn)阿里云oss上傳的示例代碼的文章就介紹到這了,更多相關(guān)springboot vue 阿里云oss上傳內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
java根據(jù)開(kāi)始時(shí)間結(jié)束時(shí)間計(jì)算中間間隔日期的實(shí)例代碼
這篇文章主要介紹了java根據(jù)開(kāi)始時(shí)間結(jié)束時(shí)間計(jì)算中間間隔日期的實(shí)例代碼,需要的朋友可以參考下2019-05-05Spring異常實(shí)現(xiàn)統(tǒng)一處理的方法
這篇文章主要介紹了Spring異常實(shí)現(xiàn)統(tǒng)一處理的方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)吧2022-12-12springcloud集成nacos?使用lb?無(wú)效問(wèn)題解決方案
這篇文章主要介紹了解決springcloud集成nacos?使用lb?無(wú)效,通過(guò)查看spring-cloud-starter-gateway?jar中的自動(dòng)配置類(lèi)的源碼,得知,該jar包中是不支持負(fù)載均衡的,需要引入spring-cloud-starter-loadbalancer?來(lái)支持,需要的朋友可以參考下2023-04-04使用Mock進(jìn)行業(yè)務(wù)邏輯層Service測(cè)試詳解
這篇文章主要介紹了使用Mock進(jìn)行業(yè)務(wù)邏輯層Service測(cè)試詳解,mock是一種模擬對(duì)象的技術(shù),用于在測(cè)試過(guò)程中替代真實(shí)的對(duì)象,通過(guò)mock,我們可以控制被模擬對(duì)象的行為和返回值,以便進(jìn)行更加精確的測(cè)試,需要的朋友可以參考下2023-08-08SpringBoot中Zookeeper分布式鎖的原理和用法詳解
Zookeeper是一個(gè)分布式協(xié)調(diào)服務(wù),它提供了高可用、高性能、可擴(kuò)展的分布式鎖機(jī)制,SpringBoot是一個(gè)基于Spring框架的開(kāi)發(fā)框架,它提供了對(duì)Zookeeper分布式鎖的集成支持,本文將介紹SpringBoot中的 Zookeeper分布式鎖的原理和使用方法,需要的朋友可以參考下2023-07-07JDK源碼分析之String、StringBuilder和StringBuffer
這篇文章主要給大家介紹了關(guān)于JDK源碼分析之String、StringBuilder和StringBuffer的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用jdk具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2018-05-05Java設(shè)計(jì)模式之初識(shí)行為型模式
今天帶大家學(xué)習(xí)Java設(shè)計(jì)模式的相關(guān)知識(shí)點(diǎn),文中對(duì)Java行為型模式做了非常詳細(xì)的介紹及代碼示例,對(duì)正在學(xué)習(xí)java的小伙伴們很有幫助,需要的朋友可以參考下2021-06-06