文件上传
在上传之前(beforeAvatarUpload)限制上传文件的格式
function beforeAvatarUpload () {
const isPPTX = file.type === 'application/vnd.openxmlformats-officedocument.presentationml.presentation'
const isPDF = file.type === 'application/pdf'
const isPPT = file.type === 'application/vnd.ms-powerpoint'
const isDOCX = file.type === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
const isDOC = file.type === 'application/msword'
const isLt2M = file.size / 1024 / 1024 < 10
if (!isPPTX&&!isPDF&&!isPPT&&!isDOCX&&!isDOC) {
// this.$message.error('上传文件只能是 .pdf .ppt .pptx .doc .docx 格式!')
}
if (!isLt2M) {
// this.$message.error('上传文件大小不能超过 10MB!')
return false
}
return isPPTX || isPDF || isPPT || isDOCX || isDOC
}
开始进行文件上传(httpRequest)
function httpRequest () {
let _this = this
let rd = new FileReader() // 创建文件读取对象
let file = data.file
var FObj = this
rd.readAsDataURL(file) // 文件读取装换为base64类型
uploadWithAccount({
}).then(function(response){
// 上傳到文件服務器,拿到文件的路徑,response:成功訊息
let fileFieldName = file.name
var _this = this;
let fileInfo = {
}
saveTestPaperInfoApi(fileInfo).then(res=>{
// 保存在本地數據庫
if(res.code==200){
FObj.loading = false
FObj.$message({
message: '上傳成功',
type: 'success'
});
this.getTestPaperList()
} else {
FObj.$message({
message: '上傳失敗',
type: 'error'
});
}
})
})
}
文件的下載和預覽
這裡以預覽pdf文件為例,然後進行下載
import axios from 'axios'
// 預覽PDF
function previewSop (url) {
axios.get(
url,
{
responseType: 'arraybuffer'}
).then(res => {
var data = res.data;
var blob = new Blob([data], {
type: 'application/pdf'});
var url = window.URL.createObjectURL(blob);
var userAgent = navigator.userAgent;
var browser = "";
var a = document.createElement('a');
var o = document.body;
if (userAgent.indexOf("Trident") > -1) {
browser = "IE";
} else {
browser = "chrome"
}
if (browser === "IE") {
a.setAttribute('href', fileServerBaseUrl + url); // fileServerBaseUrl為服務器的ip
o.appendChild(a).click()
} else {
a.setAttribute('href', url);
a.setAttribute('target', '_blank');
a.click();
}
})
}