Vue 图片上传:两种常用方法详解
Vue.js可以使用多种方式进行图片上传,下面介绍其中两种常用的方式:
- 使用第三方组件
Vue.js社区中有很多第三方组件可以方便地实现图片上传功能,如Vue-Upload、Vue-File-Upload、Vue-Cropper等。这些组件通常提供了丰富的功能,如图片剪裁、压缩、预览等,并且易于集成到Vue.js项目中。
使用方式:
首先,安装相应的组件,如使用Vue-Upload:
npm install vue-upload-component --save
在Vue.js项目中引入组件:
import VueUploadComponent from 'vue-upload-component';
export default {
components: {
'file-upload': VueUploadComponent
},
methods: {
uploadSuccess(response, file, fileList) {
console.log(response, file, fileList);
}
}
};
在Vue.js模板中使用组件:
<file-upload ref="upload"
:name="name"
:url="url"
:headers="headers"
:data="data"
:multiple="multiple"
:accept="accept"
:extensions="extensions"
:max-size="maxSize"
:with-credentials="withCredentials"
:timeout="timeout"
:auto-upload="autoUpload"
:disabled="disabled"
:drag-drop="dragDrop"
:drop-directory="dropDirectory"
:drop-directory-only="dropDirectoryOnly"
:input-id="inputId"
:tabindex="tabindex"
:capture="capture"
:camera="camera"
:instant-upload="instantUpload"
:no-input="noInput"
:input-name="inputName"
:input-accept="inputAccept"
:input-extensions="inputExtensions"
:input-multiple="inputMultiple"
:input-directory="inputDirectory"
:input-drag-drop="inputDragDrop"
:input-drop-directory="inputDropDirectory"
:input-drop-directory-only="inputDropDirectoryOnly"
:input-tabindex="inputTabindex"
:input-capture="inputCapture"
:input-camera="inputCamera"
:input-instant-upload="inputInstantUpload"
@input-file="inputFile"
@input-filter="inputFilter"
@input-clear="inputClear"
@input-replace="inputReplace"
@before-upload="beforeUpload"
@start="start"
@progress="progress"
@end="end"
@success="uploadSuccess"
@error="error"
@abort="abort">
<template slot="tip">上传图片</template>
</file-upload>
- 自定义组件实现
如果需要自定义图片上传组件,可以使用HTML5的FormData和XMLHttpRequest对象实现。具体步骤如下:
- 创建一个form标签,设置enctype属性为'multipart/form-data',并在其中添加一个input标签,type属性为'file',name属性为'file'。
<form enctype='multipart/form-data'>
<input type='file' name='file'>
</form>
- 在Vue.js组件中监听input标签的change事件,获取选择的文件。
export default {
methods: {
handleFileChange(event) {
this.file = event.target.files[0];
}
}
};
- 创建一个FormData对象,将选择的文件添加到FormData中。
export default {
methods: {
handleFileChange(event) {
this.file = event.target.files[0];
},
handleUpload() {
if (!this.file) {
return;
}
const formData = new FormData();
formData.append('file', this.file);
// 发送请求
}
}
};
- 创建XMLHttpRequest对象,设置请求方法、请求地址、请求头等信息,并发送请求。
export default {
methods: {
handleFileChange(event) {
this.file = event.target.files[0];
},
handleUpload() {
if (!this.file) {
return;
}
const formData = new FormData();
formData.append('file', this.file);
const xhr = new XMLHttpRequest();
xhr.open('POST', '/upload');
// 设置请求头信息
xhr.setRequestHeader('Content-Type', 'multipart/form-data');
xhr.setRequestHeader('Authorization', 'Bearer ' + token);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
// 上传成功
} else {
// 上传失败
}
}
};
xhr.send(formData);
}
}
};
原文地址: https://www.cveoy.top/t/topic/mv4u 著作权归作者所有。请勿转载和采集!