封装js上传方法
const OSS = require('ali-oss')
export default {
data: function() {
return {
ossParameter: {
// endpoint:'oss-accelerate.aliyuncs.com',
region: 'oss-cn-beijing',
accessKeyId: '***************',
accessKeySecret: '***************',
bucket: 'wxmg-web'
},
envJudge: '',
years: '',
formatMonth: ''
}
},
created() {},
methods: {
httpRequest(configpath, file) {
return new Promise((resolve, reject) => {
//生成上传oss
let store = new OSS(this.ossParameter)
//路径
let path = `${configpath}${file.name}`
store
.multipartUpload(path, file, {
//进度
progress: this.onProgress
})
.then(result => {
resolve(result)
})
})
},
fomatTime() {
const date = new Date()
this.years = date.getFullYear()
const month = date.getMonth() + 1
this.formatMonth = month < 10 ? '0' + month : month
if (process.env.VUE_APP_ENV_TITLE == '开发线') {
this.envJudge = 'alpha'
} else if (process.env.VUE_APP_ENV_TITLE == '测试线') {
this.envJudge = 'beta'
} else if (process.env.VUE_APP_ENV_TITLE == '正式线') {
this.envJudge = 'release'
}
},
uploadOSS(file) {
return new Promise(async (resolve, reject) => {
this.fomatTime()
let ossfileName = `book/${this.envJudge}/${this.years}/${this.formatMonth}/img/${file.name}`
this.ossParameter.bucket = 'wxmg-server'
let client = new OSS(this.ossParameter)
const res = await client.multipartUpload(ossfileName, file)
resolve(res.res)
})
},
putBuffer(html, fileName) {
return new Promise(async (resolve, reject) => {
this.fomatTime()
const ossfileName = `book/${this.envJudge}/${this.years}/${this.formatMonth}/html/${fileName}`
this.ossParameter.bucket = 'wxmg-server'
let client = new OSS(this.ossParameter)
let result = await client.put(ossfileName, new Buffer(html), {
headers: {
'Content-Disposition': 'inline',
'Content-Type': '.html' //注意:根据图片或者文件的后缀来设置,我试验用的‘.png’的图片,具体为什么下文解释
}
})
if (result) {
resolve(result.res)
}
})
}
}
}
1.上传图片到阿里OSS
图片vue
<el-upload class="image-uploader" ref="upload" action="#" :beforeUpload="beforeUpload" :show-file-list="false" :auto-upload="true" :data="form" :http-request="uploadFile" name="image">
<img v-if="imageForm.url" :src="imageForm.url" class="image" />
<i v-else class="el-icon-plus image-uploader-icon"></i>
</el-upload>
js
<script>
import ossUpload from '@/mixins/ossUpload'
export default {
mixins: [ossUpload],
data () {
return {
}
},
methods: {
beforeUpload (file) {
const isLtSize = file.size / 1024 / 1024 < 5
if (!isLtSize) {
this.$message.error('上传图片大小不能超过 5MB!')
}
return isLtSize
},
async uploadFile (data) {
const file = data.file
const result = await this.uploadOSS(file)
if (result.status == 200 && result.requestUrls) {
if (file.size >= 100 * 1024) {
this.imageForm.url = result.requestUrls[0].split('?')[0]
} else {
this.imageForm.url = result.requestUrls[0]
}
const reg = /^http:\/\/[^/]+/
if (reg.test(this.imageForm.url)) {
this.imageForm.url = this.imageForm.url.replace(/^http:\/\/[^/]+/, 'https://cdn-res.wanxue.cn')
} else {
this.imageForm.url = this.imageForm.url.replace(/^https:\/\/[^/]+/, 'https://cdn-res.wanxue.cn')
}
this.$message.success('上传成功!')
}
}
}
}
</script>
封装生成html方法
export default {
data: function() {
return {}
},
created() {},
methods: {
// 获取编辑框的 html
handleSave(domValue, docuName) {
const renderContent = domValue
// 处理得到的<html> 标签
const htmlElement = document.createElement('html')
htmlElement.setAttribute('lang', 'zh-CN')
htmlElement.setAttribute('xmlns', 'http://www.w3.org/1999/xhtml')
const headElement = document.createElement('head')
const bodyElement = document.createElement('body')
const metaElement = document.createElement('meta')
metaElement.setAttribute('charset', 'utf-8')
metaElement.setAttribute('name', 'viewport')
metaElement.setAttribute('content', 'width=device-width, initial-scale=1,user-scalable=no')
headElement.appendChild(metaElement)
headElement.appendChild(this.addLink('https://cdn.bootcss.com/github-markdown-css/2.10.0/github-markdown.min.css'))
headElement.appendChild(this.addLink('https://qncdn.wanxue.cn/static/katex/katex.min.css'))
// headElement.appendChild(
// this.addLink(
// "https://qncdn.wanxue.cn/static/katex/contrib/copy-tex.min.css"
// )
// );
const divElement = document.createElement('div')
divElement.setAttribute('class', 'markdown-body')
const styles = this.addStyle()
headElement.appendChild(styles)
divElement.innerHTML = renderContent
bodyElement.appendChild(divElement)
htmlElement.appendChild(headElement)
htmlElement.appendChild(bodyElement)
const contents = htmlElement.outerHTML // 从html对象取出字符串
// this.download(docuName, contents) // 下载
// console.log(htmlElement, contents)
return contents
},
/**生成link标签 */
addLink(url) {
const linkTag = document.createElement('link')
// linkTag.id = 'dynamic-style';
linkTag.href = url
linkTag.setAttribute('rel', 'stylesheet')
linkTag.setAttribute('media', 'all')
linkTag.setAttribute('type', 'text/css')
return linkTag
},
// 生成要下载的样式
addStyle() {
const style = document.createElement('style')
style.type = 'text/css'
try {
style.appendChild(
// document.createTextNode(
// 'table { border-spacing: 0;border-collapse: collapse;display: inline-block;overflow: auto;} table tr { background-color: #fff;border-top: 1px solid #c6cbd1} table td, table th { padding: 6px 13px; border: 1px solid #dfe2e5;}'
// )
document.createTextNode('html { overflow-y: scroll;word-break: break-all; } .markdown-body { padding:10px;font-size:14px} ')
)
} catch (ex) {}
return style
},
// 利用a标签下载文档
download(filename, content) {
const element = document.createElement('a')
// encodeURIComponent() 函数可把字符串作为 URI 组件进行编码
element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(content))
element.setAttribute('download', filename)
element.style.display = 'none'
document.body.appendChild(element)
console.log(element)
element.click()
document.body.removeChild(element)
},
getUrlname(url) {
//假如传进来的url是 http://www.qq.com/index.html?name=joey 这里一共是有3个斜杠,如果我们想获取index.html
url = url.split('?')[0] // 我们只要?号前的
let urlSlashCount = url.split('/').length // 统计有3斜杠
return url.split('/')[urlSlashCount - 1].toLowerCase() //获取数组最后一个
}
}
}
随机时间戳
//随机生成n位字符串加时间戳
export function randomTime(number) {
return Math.floor(Math.random() * Math.pow(10, number) + 1) + "_" + new Date().getTime()
}
上传富文本内容
<script>
import htmlDown from '@/mixins/htmlDown.js'
import axios from 'axios'
import { randomTime } from '@/api/util/common'
export default {
mixins: [htmlDown],
data () {
return {}
},
methods: {
async submitForm () {
const html = this.$refs.editor.getHtmlContent()// 富文本内容
let fileName = ''
if (this.isEdit) {
fileName = this.chapterId + '.html'
} else {
fileName = randomTime(5) + '.html'
}
const response = await this.putBuffer(this.handleSave(html), fileName)
if (response.status == 200 && response.requestUrls) {
const reg = /^http:\/\/[^/]+/
if (reg.test(response.requestUrls[0])) {
this.form.chapterUrl = response.requestUrls[0].replace(/^http:\/\/[^/]+/, 'https://cdn-res.wanxue.cn')
} else {
this.form.chapterUrl = response.requestUrls[0].replace(/^https:\/\/[^/]+/, 'https://cdn-res.wanxue.cn')
}
}
},
/** 获取链接的内容 */
getHtmlContent (url) {
axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8'
axios
.get(url)
.then(response => {
this.form.chapterText = response.data
this.$refs.editor.setContent(response.data)
})
.catch(error => {
console.log(error)
})
}
}
}
</script>
阿里云OSS 绑定域名访问html文件或者图片设置打开而不是打开下载
给oss绑定自己公司的域名就好,需要运营设置并申请域名
https://blog.csdn.net/tang242424/article/details/115265260?spm=1001.2101.3001.6650.1&utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7Edefault-1.highlightwordscore&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7Edefault-1.highlightwordscore