Use OSS to upload pictures or attachments in vue projectThere is no distinction here between uploading pictures and attachments; the upload process is the same; 1. Create a new oss.js file and encapsulate and use oss (need to install the ali-oss package)const OSS = require('ali-oss') const OSSConfig = { uploadHost: 'http://xxxxx.oss-cn-shenzhen.aliyuncs.com', //OSS upload addressossParams: { region: 'oss-cn-shenzhen', success_action_status: '200', // default is 200 accessKeyId: 'LTxxxxxxxxxxxxxxxvnkD', accessKeySecret: 'J6xxxxxxxxxxxxxxxxiuv', bucket: 'xxxxxxxx-czx', }, } function random_string(len) { len = len || 32 var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678' var maxPos = chars.length var pwd = '' for (let i = 0; i < len; i++) { pwd += chars.charAt(Math.floor(Math.random() * maxPos)) } return pwd } function uploadOSS(file) { return new Promise(async (resolve, reject) => { const fileName = `${random_string(6)}_${file.name}` let client = new OSS({ region: OSSConfig.ossParams.region, accessKeyId: OSSConfig.ossParams.accessKeyId, accessKeySecret: OSSConfig.ossParams.accessKeySecret, bucket: OSSConfig.ossParams.bucket, }) const res = await client.multipartUpload(fileName, file) // resolve(res) // Or return as follows: resolve({ fileUrl: `${OSSConfig.uploadHost}/${fileName}`, fileName: file.name }) }) } export { uploadOSS } 2. Use oss.js in the pageThis is a secondary encapsulation of the elementUI upload component. The component action is not used to upload pictures and attachments, but the OSS upload method is used. <template> <div class="upload-file"> <el-upload ref="fileUpload" action="" :headers="uploadProps.headers" list-type="picture-card" :show-file-list="false" :http-request="fnUploadRequest" :on-success="handleSuccess" :on-error="handleError" :before-upload="handleUpload" > <slot></slot> </el-upload> </div> </template> <script> import { getAccessToken, getRefreshToken, getAccessTokenTTL } from "@/utils/auth"; import { uploadOSS } from '@/utils/oss'; export default { name: "index", data() { return {}; }, computed: { userAccountID() { return this.$store.state.user.userAccountID; }, uploadProps() { return { // action: `${process.env.VUE_APP_BASE_API}/api/file/upload`, headers: { // The interface may require a token: "", Authorization: getAccessToken(), }, data: {}, }; }, }, methods: { handleExceed(file, fileList){ // console.log(file, fileList); this.$message.error('Upload failed, limit the upload quantity to 10 files!'); }, handleUpload(file, fileList){ // console.log(file, fileList); var testmsg = file.name.substring(file.name.lastIndexOf('.') + 1) const extension = testmsg === 'xlsx' || testmsg === 'xls' || testmsg === 'docx' || testmsg === 'doc' || testmsg === 'pdf' || testmsg === 'zip' || testmsg === 'rar' || testmsg === 'ppt' || testmsg === 'txt' const isLimit10M = file.size / 1024 / 1024 < 10 var bool = false; if(extension && isLimit10M){ bool = true; } else { bool = false; } if(!extension) { this.$message.error('Please select the attachment file type!'); return bool; } if(!isLimit10M) { this.$message.error('Upload failed, cannot exceed 10M!'); return bool; } return bool; }, handleSuccess(res) { // console.log(res); if (res) { this.$emit('fileData', res) this.$message.success("Attachment uploaded successfully!"); } }, handleError(err){ this.$message.error('Failed to upload attachment!'); }, // Upload image async fnUploadRequest(options) { try { // console.log(options); let file = options.file; // Get file let res = await uploadOSS(file) console.log(res); //Return data this.$emit("fileData", res); this.$message.success("Attachment uploaded successfully!"); } catch (e) { this.$message.error('Failed to upload attachment!'); } }, }, }; </script> <style lang="scss" scoped> ::v-deep .el-upload, .el-upload--picture-card { // width: 50px; height: 0px; border: none; line-height: 0; display: block; background: #f5f6fb; } .el-upload { width: 50px; } .img-cont { width: 50px; height: 24px; background: #f5f6fb; .img-icon { color: #ccc; } .img-text { font-size: 12px; height: 24px; color: #000; } } </style> Use the encapsulated upload component <div class="task-detail pr"> <el-form-item label="Reason for reporting" prop="taskDesc" required> <div class="flex-center upload-position"> <ImgUpload @imgData="imgData" /> <FileUpload class="ml10" @fileData="fileData" /> </div> <el-input type="textarea" v-model="ruleForm.taskDesc" placeholder="Please enter the reason for reporting" maxlength="200" @input="checkiptTaskDesc()" ></el-input> <div class="ipt-taskDesc-length">{{checkIptTaskDescLen}}/200</div> <div class="img-list mt10 flex"> <ImgZoomIn :imagesList="imagesList" @deleteImg="deleteImg"></ImgZoomIn> </div> <div class="dotted-line" v-if="imagesList.length > 0 && filesList.length > 0"></div> <div class="file-item"> <HandleFile :filesList="filesList" @deleteFile="deleteFile"></HandleFile> </div> </el-form-item> </div> The effect is as follows This is the end of this article about how vue uses OSS to upload pictures or attachments. For more relevant content about how vue uses OSS to upload pictures or attachments, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future! You may also be interested in:
|
<<: Detailed explanation of MySQL combined index method
>>: Steps to purchase a cloud server and install the Pagoda Panel on Alibaba Cloud
You must have saved other people’s web pages and l...
CentOS official website address https://www.cento...
In a page, there are many controls (elements or ta...
Table of contents 1. Installation and operation o...
When using the font-family property in CSS to ref...
This article uses an example to describe how to s...
The RHEL/CentOS series of Linux operating systems...
Code first, then text Copy code The code is as fol...
Traditionally, developers create properties in Ja...
background When you open the product details on s...
We all know that data is priceless. If we don’t b...
Main library configuration 1. Configure mysql vim...
Preface The similarities and differences between ...
Table of contents Preface 1. Use global unified o...
Table of contents MySQL crash recovery process 1....