Vue+Element el-upload文件上傳


Vue+Element el-upload文件上傳

多文件上傳 ,類型、大小限制

<h2>上傳文件</h2>
    <el-card>
        <el-upload
                   class="upload-demo"
                   ref="upload"
                   action="#"
                   :file-list="fileList"
                   accept=".pdf, .doc, .docx, .xls, .xlsx, .zip, .jpg, .png, .rar"
                   :http-request="reportFileHttpRequest"
                   :on-preview="handlePreview"
                   :on-remove="handleRemove"
                   :before-upload="beforeAvatarUpload"
                   :auto-upload="false"
                   drag
                   multiple
                   style="text-align: center">
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">將文件拖到此處,或<em>點擊上傳</em></div>
            <div class="el-upload__tip" slot="tip">只能上傳word,excel,pdf,jpg,png,zip,rar文件</div>
        </el-upload>
        <div align="center">
            <span slot="footer" class="dialog-footer" >
                <el-button style="margin-left: 10px;" size="small" @click="fileList = []">取 消</el-button>
                <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上傳到服務器</el-button>
            </span>
        </div>
    </el-card>

ref="upload" 注冊引用信息
action="#"
:file-list="fileList" 文件列表
accept=".pdf, .doc, .docx, .xls, .xlsx, .zip, .jpg, .png, .rar" 限制文件接收類型
:http-request="reportFileHttpRequest" 自定義上傳
:on-preview="handlePreview" 點擊文件列表中已上傳的文件時的鈎子
:on-remove="handleRemove" 文件列表移除文件時的鈎子
:before-upload="beforeAvatarUpload" 文件上傳之前的鈎子
:auto-upload="false" 關閉自動上傳
drag 拖拽上傳
multiple 批量上傳

// 上傳文件 此時會觸發組件的http-request
submitUpload() {
    this.$refs.upload.submit();
},
// 文件列表移除文件時的鈎子
handleRemove(file, fileList) {
    console.log(file, fileList);
},
// 點擊文件列表中已上傳的文件時的鈎子
handlePreview(file) {
    console.log(file);
},
// 文件上傳之前的鈎子
beforeAvatarUpload(file) {
    const isLt2M = file.size / 1024 / 1024 < 32;
    if (!isLt2M) {
        this.$message.error('上傳頭像圖片大小不能超過 32MB!');
    }
    return isLt2M;
},
// 自定義上傳
reportFileHttpRequest(param) {
    if (this.$refs.upload) {
        this.$refs.upload.clearFiles() // 清除上傳的文件
    }
    const _this = this
    // 開始上傳文件 新建一個formData
    const formData = new FormData();//FormData對象,添加參數只能通過append('key', value)的形式添加
    formData.append("file", param.file);//添加文件對象
    const url = 'http://***********/upload';
    axios.post(url, formData)
        .then(res => {
        axios.post(url, data)
            .then(function (resp) {
            if (resp.data.code == 200) {
                _this.$message({
                    message: '上傳成功',
                    type: 'success'
                });
            } else {
                _this.$message(resp.data.data)
            }
        })
    })
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM