Vue는 간단하고 가벼운 업로드 파일 구성 요소의 예를 캡슐화합니다.

亚连
풀어 주다: 2018-05-26 16:46:17
원래의
1357명이 탐색했습니다.

이 글에서는 간단하고 가벼운 업로드 파일 컴포넌트를 캡슐화한 Vue의 예를 주로 소개합니다. 편집자는 꽤 좋다고 생각해서 지금 공유하고 참고용으로 제공하겠습니다. 에디터 따라가서 함께 살펴볼까요

1. 이전에 겪었던 몇 가지 문제

프로젝트에서 파일을 업로드하기 위해 요구사항이 많은데, 구현을 위해 기존 UI 프레임워크를 사용하는 과정에서 그렇지 않습니다. 이유를 알 수 없는 버그가 항상 있을 것입니다. 예를 들어 특정 업로드 구성 요소를 사용하는 경우 (:multiple="false")로 명확하게 표시되지만 실제로는 여러 파일을 선택할 수 있으며 업로드 시 여러 파일이 계속 전송됩니다. (:file-list="fileList"가 추가됨) ") 속성을 사용하여 업로드 목록을 수동으로 제어하려는 경우 업로드 이벤트 this.refs.[upload (컴포넌트 참조)].submit()이 작동하지 않으며 실행할 수 없습니다. 전송됩니다. 간단히 말해서 함수를 사용하고 있는데 인터페이스 자체를 다시 작성해야 하는데, 굳이 사용하면 프로젝트에 불필요한 로직과 스타일 코드가 많이 추가될 것입니다. ...

저는 이전에 프로젝트에 Vue를 사용했습니다. 뷰 프레임워크에는 팀 내 보완 요소로 element-ui, zp-ui, iview가 포함되어 있습니다. 프레임워크는 사용하기 쉽지만 자신의 프로젝트에 사용하지 못하는 경우가 많습니다. 특히 우리 디자인 소녀가 만든 인터페이스는 기존 프레임워크와 매우 다르며, 소스 코드를 변경하는 것은 비효율적이며 쉽게 알 수 없는 버그로 이어질 수 있습니다. 그래서 시간을 내어 이 업로드 구성 요소를 캡슐화합니다.

2. 코드 및 소개

상위 컴포넌트

<template>
 <p class="content">
 <label for="my-upload">
  <span>上传</span>
 </label>
  <my-upload
   ref="myUpload"
   :file-list="fileList"
   action="/uploadPicture"
   :data="param"
   :on-change="onChange"
   :on-progress="uploadProgress"
   :on-success="uploadSuccess"
   :on-failed="uploadFailed"
   multiple
   :limit="5"
   :on-finished="onFinished">
  </my-upload>
  <button @click="upload" class="btn btn-xs btn-primary">Upload</button>
 </p>
</template>

<script>
import myUpload from &#39;./components/my-upload&#39;
export default {
 name: &#39;test&#39;,
 data(){
  return {
  fileList: [],//上传文件列表,无论单选还是支持多选,文件都以列表格式保存
  param: {param1: &#39;&#39;, param2: &#39;&#39; },//携带参数列表
  }
 },
 methods: {
  onChange(fileList){//监听文件变化,增减文件时都会被子组件调用
  this.fileList = [...fileList];
  },
  uploadSuccess(index, response){//某个文件上传成功都会执行该方法,index代表列表中第index个文件
  console.log(index, response);
  },
  upload(){//触发子组件的上传方法
  this.$refs.myUpload.submit();
  },
  removeFile(index){//移除某文件
  this.$refs.myUpload.remove(index);
  },
  uploadProgress(index, progress){//上传进度,上传时会不断被触发,需要进度指示时会很有用
  const{ percent } = progress;
  console.log(index, percent);
  },
  uploadFailed(index, err){//某文件上传失败会执行,index代表列表中第index个文件
  console.log(index, err);
  },
  onFinished(result){//所有文件上传完毕后(无论成败)执行,result: { success: 成功数目, failed: 失败数目 }
  console.log(result);
  }
 },
 components: {
  myUpload
 }
}
</script>
로그인 후 복사

상위 컴포넌트는 비즈니스 관련 로직을 처리하며, 업로드 결과를 표시할 때 인터페이스에서 숫자를 직접 조작할 수 있도록 인덱스 매개변수를 특별히 추가했습니다. . 모든 방법에 필요한 값은 아니며 필요에 따라 사용합니다.

하위 구성 요소

<template>
<p>
 <input style="display:none" @change="addFile" :multiple="multiple" type="file" :name="name" id="my-upload"/>
</p>
</template>
로그인 후 복사

파일을 업로드하세요. html 부분은 태그 쌍일 뿐입니다. 복잡성이 마음에 들지 않습니다.

<script>
export default {
 name: &#39;my-upload&#39;,
 props: {
 name: String,
 action: {
  type: String,
  required: true
 },
 fileList: {
  type: Array,
  default: []
 },
 data: Object,
 multiple: Boolean,
 limit: Number,
 onChange: Function,
 onBefore: Function,
 onProgress: Function,
 onSuccess: Function,
 onFailed: Function,
 onFinished: Function
 },
 methods: {}//下文主要是methods的介绍,此处先省略
}
</script>
로그인 후 복사

이것은 필요한 속성 값을 정의합니다. 참고로 여기에서는 메서드를 속성으로 전달할 수도 있습니다.

내가 작성한 구성 요소는 인기 있는 프레임워크에서 출시된 구성 요소만큼 완전하고 포괄적이지 않습니다. 또한 처음에 언급한 바인딩된 파일 목록을 업로드할 수 없는 문제를 해결하기 위해 최선을 다하고 싶습니다. 자세가 잘못되었습니다.) 발생한 이 문제를 해결하기 위해 파일 목록에 대한 절대적인 제어권을 갖고 싶습니다. 파일 목록도 부모가 전달해야 하는 속성으로 사용됩니다. 요소. (상위 컴포넌트의 속성 이름은 하위 컴포넌트 prop의 Camel Case 명명에 해당하는 "-"로 연결됩니다.)

3. 주요 업로드 기능

methods: {
  addFile, remove, submit, checkIfCanUpload
}
로그인 후 복사

총 1개가 있습니다. 4가지 메소드, 파일 추가, 이동 파일, 제출, 테스트(업로드 전 테스트) 외에 다음과 같이 하나씩 설명합니다.

1. 파일 추가

addFile({target: {files}}){//input标签触发onchange事件时,将文件加入待上传列表
 for(let i = 0, l = files.length; i < l; i++){
 files[i].url = URL.createObjectURL(files[i]);//创建blob地址,不然图片怎么展示?
 files[i].status = &#39;ready&#39;;//开始想给文件一个字段表示上传进行的步骤的,后面好像也没去用......
 }
 let fileList = [...this.fileList];
 if(this.multiple){//多选时,文件全部压如列表末尾
 fileList = [...fileList, ...files];
 let l = fileList.length;
 let limit = this.limit;
 if(limit && typeof limit === "number" && Math.ceil(limit) > 0 && l > limit){//有数目限制时,取后面limit个文件
  limit = Math.ceil(limit);
//  limit = limit > 10 ? 10 : limit;
  fileList = fileList.slice(l - limit);
 }
 }else{//单选时,只取最后一个文件。注意这里没写成fileList = files;是因为files本身就有多个元素(比如选择文件时一下子框了一堆)时,也只要一个
 fileList = [files[0]];
 }
 this.onChange(fileList);//调用父组件方法,将列表缓存到上一级data中的fileList属性
 },
로그인 후 복사

2.

이것은 간단합니다. 때로는 파일이 상위 구성 요소에서 분기되는 경우가 있습니다. , 인덱스를 전달하기만 하면 됩니다.

remove(index){
 let fileList = [...this.fileList];
 if(fileList.length){
 fileList.splice(index, 1);
 this.onChange(fileList);
 }
},
로그인 후 복사

3. 업로드 제출

여기에서는 가져오기 및 기본 메서드 두 가지 방법이 사용됩니다. 가져오기는 업로드 진행 상황 가져오기를 지원하지 않으므로 진행률 표시줄이 필요하지 않거나 진행 상황을 직접 시뮬레이션하거나 XMLHttpRequest를 사용하는 경우입니다. 객체가 존재하지 않으면 가져오기를 사용하여 업로드 로직을 요청하는 것이 더 간단합니다

submit(){
 if(this.checkIfCanUpload()){
 if(this.onProgress && typeof XMLHttpRequest !== &#39;undefined&#39;)
  this.xhrSubmit();
 else
  this.fetchSubmit();
 }
},
로그인 후 복사

4. 두 가지 업로드 로직 세트를 기반으로 xhrSubmit 및 fetchSubmit 두 가지 메소드가 여기에 캡슐화되어 있습니다

fetchSubmit

fetchSubmit(){
 let keys = Object.keys(this.data), values = Object.values(this.data), action = this.action;
 const promises = this.fileList.map(each => {
 each.status = "uploading";
 let data = new FormData();
 data.append(this.name || &#39;file&#39;, each);
 keys.forEach((one, index) => data.append(one, values[index]));
 return fetch(action, {
  method: &#39;POST&#39;,
  headers: {
   "Content-Type" : "application/x-www-form-urlencoded"
  },
  body: data
 }).then(res => res.text()).then(res => JSON.parse(res));//这里res.text()是根据返回值类型使用的,应该视情况而定
 });
 Promise.all(promises).then(resArray => {//多线程同时开始,如果并发数有限制,可以使用同步的方式一个一个传,这里不再赘述。
 let success = 0, failed = 0;
 resArray.forEach((res, index) => {
  if(res.code == 1){
  success++;         //统计上传成功的个数,由索引可以知道哪些成功了
  this.onSuccess(index, res);
  }else if(res.code == 520){   //约定失败的返回值是520
  failed++;         //统计上传失败的个数,由索引可以知道哪些失败了
  this.onFailed(index, res);
  }
 });
 return { success, failed };   //上传结束,将结果传递到下文
 }).then(this.onFinished);      //把上传总结果返回
},
로그인 후 복사

xhrsubmit

xhrSubmit(){
  const _this = this;
 let options = this.fileList.map((rawFile, index) => ({
 file: rawFile,
 data: _this.data,
    filename: _this.name || "file",
    action: _this.action,
    onProgress(e){
     _this.onProgress(index, e);//闭包,将index存住
    },
    onSuccess(res){
     _this.onSuccess(index, res);
    },
    onError(err){
     _this.onFailed(index, err);
    }
  }));
 let l = this.fileList.length;
 let send = async options => {
 for(let i = 0; i < l; i++){
  await _this.sendRequest(options[i]);//这里用了个异步方法,按次序执行this.sendRequest方法,参数为文件列表包装的每个对象,this.sendRequest下面紧接着介绍
 }
 };
 send(options);
},
로그인 후 복사

ee ee emely emelt-ui

sendRequest(option){

 const _this = this;
  upload(option);

 function getError(action, option, xhr) {
  var msg = void 0;
  if (xhr.response) {
   msg = xhr.status + &#39; &#39; + (xhr.response.error || xhr.response);
  } else if (xhr.responseText) {
   msg = xhr.status + &#39; &#39; + xhr.responseText;
  } else {
   msg = &#39;fail to post &#39; + action + &#39; &#39; + xhr.status;
  }

  var err = new Error(msg);
  err.status = xhr.status;
  err.method = &#39;post&#39;;
  err.url = action;
  return err;
 }

 function getBody(xhr) {
  var text = xhr.responseText || xhr.response;
  if (!text) {
   return text;
  }

  try {
   return JSON.parse(text);
  } catch (e) {
   return text;
  }
 }

 function upload(option) {
  if (typeof XMLHttpRequest === &#39;undefined&#39;) {
   return;
  }

  var xhr = new XMLHttpRequest();
  var action = option.action;

  if (xhr.upload) {
   xhr.upload.onprogress = function progress(e) {
    if (e.total > 0) {
     e.percent = e.loaded / e.total * 100;
    }
    option.onProgress(e);
   };
  }

  var formData = new FormData();

  if (option.data) {
   Object.keys(option.data).map(function (key) {
    formData.append(key, option.data[key]);
   });
  }

  formData.append(option.filename, option.file);

  xhr.onerror = function error(e) {
   option.onError(e);
  };

  xhr.onload = function onload() {
   if (xhr.status < 200 || xhr.status >= 300) {
    return option.onError(getError(action, option, xhr));
   }

   option.onSuccess(getBody(xhr));
  };

  xhr.open(&#39;post&#39;, action, true);

  if (option.withCredentials && &#39;withCredentials&#39; in xhr) {
   xhr.withCredentials = true;
  }

  var headers = option.headers || {};

  for (var item in headers) {
   if (headers.hasOwnProperty(item) && headers[item] !== null) {
    xhr.setRequestHeader(item, headers[item]);
   }
  }
  xhr.send(formData);
  return xhr;
 }
}
로그인 후 복사
의 업로드 소스 코드를 기반으로합니다. onBefore 메소드를 실행하고 false를 반환하거나 파일 목록이 비어 있으면 요청이 전송되지 않습니다.

코드 부분이 완료되었습니다. on-progress 속성이 존재하고 XMLHttpRequest 객체에 액세스할 수 있는 한 요청은 기본 메서드를 사용하여 전송됩니다( 진행 상황은 표시되지 않습니다).

위 내용은 제가 여러분을 위해 정리한 내용입니다. 앞으로 도움이 되길 바랍니다.

관련 기사:

Ajax 양식 비동기 파일 업로드 예제 코드

드롭다운 메뉴의 캐스케이드 동작


Ajax는 지방과 도시의 3단계 캐스케이드를 구현합니다



위 내용은 Vue는 간단하고 가벼운 업로드 파일 구성 요소의 예를 캡슐화합니다.의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!