浅谈vue组件el-upload实现上传单个或多个文件

不得不说vue和elmentui组件配合真是好用到爆,这段时间在优化代码,整理一下项目当中遇到的难点,有一个页面是是要上传文件到后台,文件类型有图片、word、pdf文件。

上传单张图片只需要参考elementui官方文档即可,也可以看下边的例子:

<el-upload :action="this.$basePath+ '/notes/sysFile/upload'"

          :headers="{token: sessionId}" :show-file-list="false" :on-success="uploadSuccess" :on-error="uploadError">

  <img class="photo" :src="imgPath"/>

</el-upload>

在上传成功的函数里这样写:

uploadSuccess:function (response, file, fileList) {

console.log(response)

this.imgPath =this.$basePath + response.info.fileName //这是核心代码,将上传的路径复制给放图片的容器即可

},

如果是上传多个文件,那就仔细看我下边的代码,真的是踩了好多次坑才对el-upload组件里有一个file-list属性,专门是针对上传多个文件所使用的,存放的是上传的文件的列表,废话不多说,直接上代码:

<el-upload :action="this.$basePath+ '/notes/sysFile/upload'"

          accept=".jpg,.jpeg,.mp3,.mp4,.png,.gif,.bmp,.pdf,.JPG,.JPEG,.PBG,.GIF,.BMP,.PDF" ref="upload"

          :headers="{token: sessionId}" :on-success="addUploadSuccess" :on-error="uploadError"

          :file-list="fileList">

  <el-button size="small" type="primary" slot="trigger">选择文件

</el-upload>

我们可以将上传的文件保存在一个list列表里边,直到文件选择完毕,再将这个list集合传给后台就可以了,上传文件成功的函数里是这样写的:

addUploadSuccess:function (response, file, fileList) {

console.log(response)

this.fileInfo.filesList =makeUrls(fileList)

},

因为项目里不只是一处地方用到了上传文件,所以可以把上传函数写到一个方法里,方便其他地方调用

function makeUrls(fileList) {

let urls = []

fileList.forEach( item => {

// urls.push(item.response.info.fileName)

    urls.push(item.response ? item.response.info.fileName : item.fileName)

})

return urls

}

传给后台的参数直接在data里边用这样的写法files:this.fileInfo.filesList就行了,

以上就是一种上传文件的写法,仅供参考,希望能对需要的朋友有所帮助。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容