vuejs怎麼實現上傳檔案

2021-09-25 19:00:21

vuejs實現上傳檔案的方法:1、建立vue頁面程式碼;2、通過「beforeUpload(file){...}」方法實現上傳之前的大小校驗;3、實現上傳檔案的相關邏輯即可。

本文操作環境:Windows7系統、vue2.9.6版,DELL G3電腦。

vuejs怎麼實現上傳檔案?

vue實現檔案上傳功能

vue 檔案上傳,供大家參考,具體內容如下

首先 先說一下想要實現的效果

就如截圖所見,需要將企業和需要上傳的檔案提交到後臺處理,那麼接下來就說如何實現

vue 實現

vue 頁面程式碼

<el-upload
class="upload-demo"
ref="upload"
action="doUpload"
:limit="1"
:file-list="fileList"
:before-upload="beforeUpload">
<el-button slot="trigger" size="small" type="primary">選取檔案</el-button>
<a href="./static/moban.xlsx" rel="external nofollow" download="模板"><el-button size="small" type="success">下載模板</el-button></a>
<!-- <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上傳到伺服器</el-button> -->
<div slot="tip" class="el-upload__tip">只能上傳excel檔案,且不超過5MB</div>
<div slot="tip" class="el-upload-list__item-name">{{fileName}}</div>
</el-upload> 
<span slot="footer" class="dialog-footer">
<el-button @click="visible = false">取消</el-button>
<el-button type="primary" @click="submitUpload()">確定</el-button>
</span>

上傳之前的大小校驗

beforeUpload(file){
 debugger
 console.log(file,'檔案');
 this.files = file;
 const extension = file.name.split('.')[1] === 'xls'
 const extension2 = file.name.split('.')[1] === 'xlsx'
 const isLt2M = file.size / 1024 / 1024 < 5
 if (!extension && !extension2) {
  this.$message.warning('上傳模板只能是 xls、xlsx格式!')
  return
 }
 if (!isLt2M) {
  this.$message.warning('上傳模板大小不能超過 5MB!')
  return
 }
 this.fileName = file.name;
 return false // 返回false不會自動上傳
 },

手動上傳確認提交

submitUpload() {
 debugger
 console.log('上傳'+this.files.name)
 if(this.fileName == ""){
  this.$message.warning('請選擇要上傳的檔案!')
  return false
 }
 let fileFormData = new FormData();
 fileFormData.append('file', this.files, this.fileName);//filename是鍵,file是值,就是要傳的檔案,test.zip是要傳的檔名
 let requestConfig = {
  headers: {
  'Content-Type': 'multipart/form-data'
  },
 }
 this.$http.post(`/basedata/oesmembers/upload?companyId=`+this.company, fileFormData, requestConfig).then((res) => {
  debugger
  if (data && data.code === 0) {
  this.$message({
  message: '操作成功',
  type: 'success',
  duration: 1500,
  onClose: () => {
  this.visible = false
  this.$emit('refreshDataList')
  }
  })
  } else {
  this.$message.error(data.msg)
  }
 }) 
 }

後臺

/**
 * 上傳檔案
 */
 @PostMapping("/upload")
 @RequiresPermissions("basedata:oesmembers:upload")
 public R upload(@RequestParam("file") MultipartFile file, @RequestParam("companyId") Integer companyId) {
 System.out.println(companyId);
 if (file.isEmpty()) {
  throw new RRException("上傳檔案不能為空");
 }
 //上傳檔案 相關邏輯
 
 return R.ok();
}

推薦:《》

以上就是vuejs怎麼實現上傳檔案的詳細內容,更多請關注TW511.COM其它相關文章!