vue webuploader 파일 업로드 구성 요소 개발
19643 단어 vuewebuploader
패키지 구성 요소
바 이 두 가 제공 하 는 webuploader.js,Uploader.swf 도입
css 스타일 은 구성 요소 에 직접 적 혀 있 습 니 다.
<template>
<div>
<div id="list" class="uploader-list"></div>
<div id="wrapper">
<div class="uploader-container">
<div :id="id" limitSize="1" :ext="ext"></div>
<el-button style="margin-bottom:10px;float:left;" size="small" :loading="uploadLoading" type="success" @click="start"> </el-button>
<el-button style="margin-left: 20px;margin-bottom:10px;float:left;" :disabled="stopBtn" size="small" type="danger" @click="stop"> </el-button>
</div>
</div>
<div class="el-upload__tip">{{tip}}</div>
<div class="file-list">
<ul class="el-upload-list el-upload-list--text">
<li v-for="file in fileList" :class="['el-upload-list__item', 'is-' + file.status]" :key="file">
<a class="el-upload-list__item-name">
<i class="el-icon-document"></i>{{file.name}}
</a>
<label class="el-upload-list__item-status-label">
<i :class="{'el-icon-upload-success': true,'el-icon-circle-check': listType === 'text',
'el-icon-check': ['picture-card', 'picture'].indexOf(listType) > -1}"></i>
</label>
<i class="el-icon-close" @click="removeFile(file)"></i>
<el-progress
v-if="file.status === 'uploading'"
:type="listType === 'picture-card' ? 'circle' : 'line'"
:stroke-width="listType === 'picture-card' ? 6 : 2"
:percentage="file.percentage">
</el-progress>
</li>
</ul>
</div>
</div>
</template>
<script>
import '../js/jquery.js'
import '../js/webuploader.js'
import { Base64 } from 'js-base64'
import CryptoJS from 'crypto-js';
export default{
name: 'fileUpload',
props: {
id: {
type: String,
default: function(){
return "filePicker";
}
},
//
tip: {
type: String,
default: function(){
return "";
}
},
//
ext: {
type: String,
default: function(){
return "jpg,jpeg,png,pdf,mp4,avi.mp3";
}
},
//
chunkSize: {
type: Number,
default: function(){
return 2097152;
}
},
//
chunkRetry: {
type: Number,
default: function(){
return 1;
}
},
//
auto: {
type: Boolean,
default: function(){
return false;
}
},
//
sizeLimit: {
type: Number,
default: function(){
return 209715200;
}
},
//
countLimit: {
type: Number,
default: function(){
return 5;
}
}
},
data(){
return{
appId: AppConfig.appId,
securityKey: AppConfig.securityKey,
checkUrl: AppConfig.checkUrl,
uploadUrl: AppConfig.uploadUrl,
mergeUrl: AppConfig.mergeUrl,
previewName: ' ',
wul_fileMd5: '',
wul_size: 0,
wul_fileName: '',
wul_chunk: 0,
wul_uploader: '',
fileList: [],
listType: 'text',
percentage: 0,
fileObject: {
uid: '',
name: '',
ext: '',
type: '',
status: '',
percentage: 0,
url: ''
},
uploadLoading: false,
stopBtn: true
}
},
methods: {
/**
*
* @returns {Array|*}
*/
getFileList: function(){
return this.fileList;
},
//
wul_init: function() {
//
this.wul_uploader.on('filesQueued', function (files) {
if (files.length > 1) {
this.$message({
message: ' ',
type: 'error'
});
for (var i = 0; i < files.length; i++) {
this.wul_uploader.cancelFile(files[i]);
}
this.wul_uploader.reset();
this.wul_fileMd5 = "";
this.wul_size = 0;
this.wul_fileName = "";
this.wul_chunk = 0; //
}else{
if( this.fileList.length == this.countLimit ){
this.$message({
message: ' ',
type: 'error'
});
}else{
//
let file = {
uid: Date.now() + this.tempIndex++,
name: files[0].name,
type: files[0].type,
ext: files[0].ext,
status: "ready",
percentage: 0
}
this.fileObject = file;
this.fileList.push(this.fileObject);
}
}
}.bind(this));
//
this.wul_uploader.on('error', function (type) {
debugger
if (type == 'Q_EXCEED_SIZE_LIMIT') {
this.$message({
message: ' ',
type: 'error'
});
}
if (type == 'Q_TYPE_DENIED') {
this.$message({
message: ' , ',
type: 'error'
});
}
if (type == 'F_EXCEED_SIZE') {
this.$message({
message: " " + this.sizeLimit / 1024 / 1024 + "M",
type: 'error'
});
}
}.bind(this));
//
this.wul_uploader.on('uploadProgress', function (file, percentage) {
this.percentage = percentage * 100;
this.fileObject.status = "uploading";
this.fileObject.percentage = this.percentage;
console.log(this.fileObject.percentage);
}.bind(this));
//
this.wul_uploader.on('uploadAccept', function (object, ret) {
if (ret.responseCode != 0) {
this.wul_uploader.cancelFile(this.wul_uploader.getFiles()[0].id);
}
});
this.wul_uploader.on('uploadBeforeSend', function(object, data, headers) {
console.log(data);
});
},
option: function(key, val) {
this.wul_uploader.option(key, val);
var options = this.wul_uploader.options;
this.wul_uploader.destroy(); // uploader
this.wul_uploader = WebUploader.create(options);
this.wul_init();
},
start: function(){
if(this.wul_uploader.getFiles()[0] != null) {
this.wul_uploader.upload(this.wul_uploader.getFiles()[0].id);
this.uploadLoading = true;
this.stopBtn = false;
} else {
this.$message({
message: " ",
type: 'error'
});
}
},
stop: function(){
this.wul_uploader.cancelFile(this.wul_uploader.getFiles()[0].id);
},
removeFile: function(file){
this.fileList.splice(this.fileList.indexOf(file), 1);
},
change: function(){
this.option('accept', {
title: 'Images',
extensions: 'gif,jpg,jpeg,bmp,png'
});
}
},
mounted(){
WebUploader.Uploader.register({
"before-send-file": "beforeSendFile",
"before-send": "beforeSend",
"after-send-file": "afterSendFile",
}, {
beforeSendFile: function (file) {
var deferred = WebUploader.Deferred();
this.wul_uploader.md5File(file).then(function (val) {
this.wul_fileMd5 = val;
this.wul_size = file.size;
this.wul_fileName = file.name;
var timestamp = Date.parse(new Date()) / 1000;
var signParam = "{chunkSize=" + this.chunkSize + ", fileMd5=" + this.wul_fileMd5 + ", size=" + this.wul_size + ", timestamp=" + timestamp + "}";
var sign = Base64.encode(CryptoJS.HmacSHA1(signParam, this.securityKey));
//
jQuery.ajax({
type: "POST",
//
url: this.checkUrl,
data: {
//
size: this.wul_size,
//
fileMd5: this.wul_fileMd5,
//
chunkSize: this.chunkSize,
//
sign: sign,
// id
appId: this.appId,
//
timestamp: timestamp
},
dataType: "json",
//
error: function (XMLHttpRequest, textStatus, errorThrown) {
this.$message({
message: " ...",
type: 'error'
});
this.uploadLoading = false;
this.stopBtn = true;
}.bind(this),
success: function (response) {
if (response.responseCode == 0) { //
this.wul_chunk = response.chunk;
deferred.resolve();
} else { // ,
this.wul_uploader.cancelFile(file); //
this.$message({
message: " , ",
type: 'error'
});
deferred.resolve();
this.uploadLoading = false;
this.stopBtn = true;
}
}.bind(this)
});
return deferred.promise();
}.bind(this));
return deferred.promise();
}.bind(this),
beforeSend: function (block) {
var deferred = WebUploader.Deferred();
if (block.chunk < this.wul_chunk) {
return deferred.reject();
}
this.wul_uploader.md5File(block.blob).then(function (chunkMd5) {
var timestamp = Date.parse(new Date()) / 1000;
var signParam = '{chunk=' + block.chunk + ', chunkMd5=' + chunkMd5 + ', chunkSize=' + this.chunkSize + ', fileMd5=' + this.wul_fileMd5 + ', size=' + this.wul_size + ', timestamp=' + timestamp + '}';
var signTemp = CryptoJS.HmacSHA1(signParam, this.securityKey);
var sign = Base64.encode(signTemp); // sign
this.wul_uploader.options.formData = {
'timestamp': timestamp,
'appId': this.appId,
'chunk': block.chunk,
'chunkSize': this.chunkSize,
'fileMd5': this.wul_fileMd5,
'chunkMd5': chunkMd5,
'size': this.wul_size,
'sign': sign
};
deferred.resolve();
}.bind(this))
return deferred.promise();
}.bind(this),
afterSendFile: function (file) {
var timestamp = Date.parse(new Date()) / 1000;
var signParam = "{chunkSize=" + this.chunkSize + ", fileMd5=" + this.wul_fileMd5 + ", fileName=" + file.name + ", size=" + this.wul_size + ", timestamp=" + timestamp + "}";
var sign = Base64.encode(CryptoJS.HmacSHA1(signParam, this.securityKey));
// ,
jQuery.ajax({
type: "POST",
url: this.mergeUrl,
data: {
appId: this.appId,
fileMd5: this.wul_fileMd5,
fileName: file.name,
chunkSize: this.chunkSize,
sign: sign,
size: this.wul_size,
timestamp: timestamp
},
success: function (response) {
if (response.responseCode == 0) {
this.fileObject.status = "success";
this.fileObject.percentage = 100;
this.fileObject.url = response.filePath;
} else {
this.fileObject.status = "exception";
this.$message({
message: " , :" + response.responseMsg,
type: 'error'
});
}
this.uploadLoading = false;
this.stopBtn = true;
this.wul_uploader.reset();
this.wul_fileMd5 = "";
this.wul_size = 0;
this.wul_fileName = "";
this.wul_chunk = 0; //
}.bind(this)
});
}.bind(this)
});
this.wul_uploader = WebUploader.create({
// swf
swf: '../js/Uploader.swf',
// 。
server: this.uploadUrl,
//
pick: {
"id": "#" + this.id,
"innerHTML": this.previewName
},
//
auto: this.auto,
//
disableGlobalDnd: true,
//
paste: '#wrapper',
//
dnd: '#wrapper',
//
chunked: true,
// 2M
chunkSize: this.chunkSize,
//
chunkRetry: this.chunkRetry,
//
compress: false,
// 10 ,
fileNumLimit: 10,
//
prepareNextFile: true,
//
fileSingleSizeLimit: this.sizeLimit,
//
threads : 1,
//
accept: {
title: "access",
extensions: this.ext
}
});
this.wul_init();
}
}
</script>
<style>
/* ----------------Reset Css--------------------- */
html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code, del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var, b, u, i, center, dl, dt, dd, ol, ul, li,
fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, figcaption, figure, footer, header, hgroup, menu, nav, section, summary,
time, mark, audio, video, input {
margin: 0;
padding: 0;
border: none;
outline: 0;
font-size: 100%;
font: inherit;
vertical-align: baseline;
}
html, body, form, fieldset, p, div, h1, h2, h3, h4, h5, h6 {
-webkit-text-size-adjust: none;
}
article, aside, details, figcaption, figure, footer, header, hgroup, menu, nav, section {
display: block;
}
body {
font-family: arial, sans-serif;
}
ol, ul {
list-style: none;
}
blockquote, q {
quotes: none;
}
blockquote:before, blockquote:after, q:before, q:after {
content: '';
content: none;
}
ins {
text-decoration: none;
}
del {
text-decoration: line-through;
}
table {
border-collapse: collapse;
border-spacing: 0;
}
/* ------------ */
#wrapper {
width: 100%;
margin: 0 auto;
height: 35px;
}
.img-preview {
width: 160px;
height: 90px;
margin-top: 1em;
border: 1px solid #ccc;
}
.cropper-wraper {
position: relative;
}
.upload-btn {
background: #ffffff;
border: 1px solid #cfcfcf;
color: #565656;
padding: 10px 18px;
display: inline-block;
border-radius: 3px;
margin-left: 10px;
cursor: pointer;
font-size: 14px;
position: absolute;
right: 1em;
bottom: 2em;
}
.upload-btn:hover {
background: #f0f0f0;
}
.uploader-container{
width: 100%;
font-size: 10px;
}
.webuploader-container {
position: relative;
width: 100px;
height: 21px;
float: left;
}
.webuploader-element-invisible {
position: absolute !important;
clip: rect(1px 1px 1px 1px); /* IE6, IE7 */
clip: rect(1px,1px,1px,1px);
}
.webuploader-pick {
position: relative;
display: inline-block;
cursor: pointer;
background: #00b7ee;
padding: 6px 15px;
color: #fff;
text-align: center;
border-radius: 3px;
overflow: hidden;
}
.webuploader-pick-hover {
background: #00a2d4;
}
.webuploader-pick-disable {
opacity: 0.6;
pointer-events:none;
}
.file-list{
width: 100%;
}
</style>
2.구성 요소 내 보 내기
var fileUpload = require('./src/file_upload.vue');
module.exports = {
fileUpload
}
데모 인용 방식
<template>
<div>
<el-card class="box-card">
<fileUpload ref="fileUpload" :ext="ext" :countLimit="5" :tip="tip">aaa</fileUpload>
</el-card>
</div>
</template>
<script>
import {fileUpload} from '@/components/fileUpload/index.js'
export default{
name: 'hello',
components: {fileUpload},
data(){
return{
fileList: [],
ext: 'png,jpg,jpeg,mp3,mp4,pdf',
tip: ' png/jpg/jpeg/mp3/mp4/pdf, 200M'
}
},
created(){
},
methods: {
getFileList: function(){
this.fileList = this.$refs.fileUpload.getFileList();
console.log(this.fileList);
}
}
}
</script>
4.운행 효과 도이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Fastapi websocket 및 vue 3(Composition API)1부: FastAPI virtualenv 만들기(선택 사항) FastAPI 및 필요한 모든 것을 다음과 같이 설치하십시오. 생성main.py 파일 및 실행 - 브라우저에서 이 링크 열기http://127.0.0.1:...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.