Giter Site home page Giter Site logo

vue-file-upload's Introduction

vue-file-upload

NPM version npm download

vue1.x版本 可安装[email protected]版本
vue2.x版本 可安装当前最新版本

vue.js ,vue-loader 上传文件,vue-file-upload 代码里面包含demo,运行:

yarn install && yarn start

install

npm

npm install --save vue-file-upload

CommonJS

var VueFileUpload = require('vue-file-upload');
//es6
import VueFileUpload from 'vue-file-upload';

属性(Props)

//目标服务器地址
url:{
  type:String,
  required:true
},
//最大文件上传数
max:{
  type:Number,
  default:Number.MAX_VALUE
},
//文件名称(服务端识别的上传文件名)
name:{
  type:String,
  default:'file'
},
//自动上传
autoUpload:{
  type:Boolean,
  default:false
},
//支持多选文件上传
multiple:{
  type:Boolean,
  default:false
},
//每新增一个待上传文件回调函数
onAdd:{
    type:Function,
    default:noop
},
//过滤函数
filters:{
  type:Array,
  default:()=>{
    return new Array();
  }
},
//请求附带参数
requestOptions:{
  type:Object,
  default:()=>{
    return{
      formData:{},
      headers:{},
      responseType:'json',
      withCredentials:false
    }
  }
},
//文件上传状态回调函数
events:{
  type:Object,
  default:()=>{
    return {
      onProgressUpload:noop(file,progress:number),//上传进度回调
      onCompleteUpload:noop(file,response,status,headers),//上传完成回调,不论成功或失败都调用
      onErrorUpload:noop(file,response,status,headers),//上传失败回调
      onSuccessUpload:noop(file,response,status,headers),//上传成功回调
      onAbortUpload:noop(file,response,status,headers),//取消上传
      onAddFileFail:noop(file,failFilter:array),//添加待上传文件失败回调,会通过filters过滤函数校验,不通过回调此函数
      onAddFileSuccess:noop(file)//添加待上传文件成功回调
    }
  }
}

按钮名称说明

<vue-file-upload>
    <span slot="label">上传文件</span>
</vue-file-upload>

文件属性说明(file)

const file = {
  name:"文件名称",//文件名称
  size:123,//文件大小
  type:"image/jpeg",//文件类型
  isReady: false,//,点击上传后,即将准备好上传
  isUploading:false,//正在上传
  isUploaded:false,//上传后
  isSuccess:false,//成功上传
  isCancel:false,//取消上传
  isError:false,//上传失败
  progress:0,//上传进度
}

//file 函数(method)
file.upload(); //上传该文件
file.cancel();//取消上传
file.remove();//移除该文件

方法(methods)

this.$refs.vueFileUploader.uploadAll()//上传所有队列中的文件
this.$refs.vueFileUploader.clearAll()//清空队列文件
this.$refs.vuefileUploader.setFormDataItem( key, value );//设置formdata

ES6

app.vue

<template lang="jade">
vue-file-upload(url='upload.do',
  ref="vueFileUploader",
  v-bind:filters = "filters",
  v-bind:events = 'cbEvents',
  v-bind:request-options = "reqopts",
  v-on:onAdd = "onAddItem")
    span(slot="label") 选择文件
table
  thead
    tr
      th name
      th size
      th progress
      th status
      th action
  tbody
    tr(v-for='file in files')
      td(v-text='file.name')
      td(v-text='file.size')
      td(v-text='file.progress')
      td(v-text='onStatus(file)')
      td
        button(type='button',@click="uploadItem(file)") 上传
button(type='button',@click="uploadAll") 上传所有文件
button(type='button',@click="clearAll") 清空文件列表
</template>
<script>
import VueFileUpload from 'vue-file-upload';
export default{
  data(){
    return{
      files:[],
      //文件过滤器,只能上传图片
      filters:[
        {
          name:"imageFilter",
          fn(file){
              var type = '|' + file.type.slice(file.type.lastIndexOf('/') + 1) + '|';
              return '|jpg|png|jpeg|bmp|gif|'.indexOf(type) !== -1;
          }
        }
      ],
      //回调函数绑定
      cbEvents:{
        onCompleteUpload:(file,response,status,header)=>{
          console.log(file);
          console.log("finish upload;")
        }
      },
      //xhr请求附带参数
      reqopts:{
        formData:{
          tokens:'tttttttttttttt'
        },
        responseType:'json',
        withCredentials:false
      }
    }
  },
  mounted(){
    //设置formData数据
    this.$refs.vueFileUploader.setFormDataItem('authorization',"123");
  },
  methods:{
    onStatus(file){
      if(file.isSuccess){
        return "上传成功";
      }else if(file.isError){
        return "上传失败";
      }else if(file.isUploading){
        return "正在上传";
      }else{
        return "待上传";
      }
    },
    onAddItem(files){
        console.log(files);
        this.files = files;
    },
    uploadItem(file){
      //单个文件上传
      file.upload();
    },
    uploadAll(){
      //上传所有文件
      this.$refs.vueFileUploader.uploadAll();
    },
    clearAll(){
      //清空所有文件
      this.$refs.vueFileUploader.clearAll();
    }
  },
  components:{
    VueFileUpload
  }
}
</script>

vue-file-upload's People

Contributors

gd4ark avatar kitayoshi avatar marchfantasy avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

vue-file-upload's Issues

想了解一下,浏览器的支持情况

您好!项目中原先使用的AjaxFileUpload,但是发现在IE9里面无法携带自定义的header参数(spring security的安全校验),导致了再IE9里面文件上传被服务端当成了未授权操作。
看到您这个vue插件,想了解一下兼容性问题

error when run dev

hi,
when i run your project, error exist, can you help me fix this issue ?? thanks ~

$ npm run dev

[email protected] dev F:\vue\loadfile1\vue-file-upload
webpack-dev-server --hot --inline --content-base ./demo

'webpack-dev-server' ▒▒▒▒▒ڲ▒▒▒▒ⲿ▒▒▒Ҳ▒▒▒ǿ▒▒▒▒еij▒▒▒
▒▒▒▒▒▒▒▒▒ļ▒▒▒

npm ERR! Windows_NT 6.1.7601
npm ERR! argv "F:\nodejs\node.exe" "F:\nodejs\node_modules\npm\bin\npm-cli.js" "run" "dev"
npm ERR! node v6.10.3
npm ERR! npm v3.10.10
npm ERR! code ELIFECYCLE
npm ERR! [email protected] dev: webpack-dev-server --hot --inline --content-base ./demo
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] dev script 'webpack-dev-server --hot --inline --content-base ./demo'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the vue-file-upload package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR! webpack-dev-server --hot --inline --content-base ./demo
npm ERR! You can get information on how to open an issue for this project with:
npm ERR! npm bugs vue-file-upload
npm ERR! Or if that isn't available, you can get their info via:
npm ERR! npm owner ls vue-file-upload
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR! F:\vue\loadfile1\vue-file-upload\npm-debug.log

添加了slot的label后, options里面的自定义headers无法生效

<vue-file-upload
  ref="lrFrontUploader"
  :url="uploadUrl"
  :filters="uploadFilters"
  :events="lrFrontUploadEvents"
  :request-options="requestOptions"
  :auto-upload="true">
    <span slot="label">上传</span>
  </vue-file-upload>
        // 上传文件xhr请求参数
        requestOptions: {
          formData: {},
          responseType: 'json',
          withCredentials: false,
          headers: {
            'customHeader': 'aaa'
          }
        }

以上代码后,请求的header里面没有customHeader

只要把<span slot="label">上传</span>去掉后,请求的header里就会添加上customHeader

  "dependencies": {
    "vue": "^2.5.2",
    "vue-router": "^3.0.1",
    "vuex": "^3.0.1",
    "vue-file-upload": "^0.1.6",
    "axios": "^0.17.1",
    "qs": "^6.5.1",
    "element-ui": "^2.0.4",
    "lodash": "^4.17.4",
    "raven-js": "^3.20.0"
  }
    "webpack": "^3.6.0"

可否增加一个函数用于重置组件状态

问题主要是我使用的时候没有destroy的过程导致他不会自动清空队列。挨个调用remove()好像太麻烦了。
看源码发现原来类里已经提供了这样一个方法,于是就直接调用了。

另外还有一个问题是:你的组件监听input的change事件来更新文件队列。当我选择了一个文件加入,再用remove方法把它从队列中清除后,input的value没有改变,导致无法再次选择这个文件来把它添加到队列中。这个问题在demo里就存在。

目前的解决方案是添加以下两行手动重置组件状态:

this.$refs.uploader.$refs.fileInput.value = '';
this.$refs.uploader.fileUploader.clearQueue();

按理说我不该直接操作组件里封装的内容的,希望能添加一个重置的方法。

无法将vue绑定的数据放到formdata中发送给服务器

data() {
return {
newKeyword:'',
keywords:[],
category:'123',
files: [],
//xhr请求附带参数
reqopts:{
formData:{
category: this.category,
keywords: this.keywords,
testString:'test',
testArray:[1,2,3],
},
responseType:'json',
withCredentials:false
}
}
},

上面这段代码中,category和keyword都是vue里的data,都是被绑定到dom上的。但是放在formdata中,keywords和category最后都会显示undefined。

那应该怎么自定义需要发送的数据(比如array)给服务器呢?

Option to change style and set custom class

It would be nice to be able to change how the file button looks, instead of always using the default green button set by CSS inside the Vue component. I'd suggest not setting style in the component file and adding a prop to add custom classes to the input file tag.
Other than that, you did a great job. This is the best Vue file upload component I've tried. Sorry I don't speak chinese.

可以显示图片预览吗?

在下有2个问题:多谢回答

  1. 可以显示图片预览吗?
  2. 支持上传进度吗?
    非常感谢!

PS: 这里没有服务器不方便测试。

问下小米手机是不是不支持

我pc上好好的,但是做成cordova然后文件选择上传,file是空的,获取不到上传文件。不知道是不支持,还是我自己的问题!你们遇到了吗

单个文件上传的时候,有时候file.upload没法继续触发

在单传的时候,如果上一张还没传完,我立刻选择下一张(选完后我触发file.upoload),或者不断选多张(动作够快),这时候,只会处理到上传第一张,后面选择的都没有动作,待上传、有办法解决这种吗?
主要是我们的场景太奇葩啦,没法一次性全部去传。场景大概如下:选完图片,先向后端获取一个上传地址和当前这个图片的重命名,我接下来再传图片的附带参数去修改这些值,改完再触发file.upload....每张图片都需要后端重命名,而且,在这一步,后端那边还要核对上传图片的名字对不对,造成我无法全部改名后再自己批量传。。。无奈。

我感觉批量上传的时候,上传队列时,每一个文件能有一个上传前的方法应该就可以解决,哈哈。

如果可以的话,希望将title的部分改为slot

我希望使用svg作为按钮图片,
希望能够自定义按钮部分的内容,
将title部分设置为 slot挺好的。

<span class="vue-file-upload">
  <i v-if='icon != null' v-bind:class='rendIcon'></i>
  <slot>{{label}}</slot>
  <input ref="fileInput" type="file" name="file">
</span>

some picture can't upload in wechat

I have find some picture can't upload in wechat(android), the netWork express that wechat can't correct load some picture because lack of "base 64".
I don't know how to resolve the problem in vue-file-upload ----

and thanks your code(Maybe I should use Chinese to express)

上传完成后,我怎么重新上传

我文件上传成功了,队列结束了,
然后我又把图片删除了(图片即使上传的)从files数组里删除,怎么再重新上传图片,我选择了文件没反应
源代码this.fileUploader.clearQueue()清除队列的,没发现重置的
请教下怎么处理

多个上传按钮,是共用一个FileList么?

多个上传按钮,是共用一个FileList么?
我看源码(src/vue-file-upload.vue)里是这样写的

<input ref="fileInput" type="file" name="file">
var elTargetFiles = _.isHTML5() ? this.$refs.fileInput.files :this.$refs.fileInput;

这个ref是写死的,那多个按钮就是调用的就是同一个fileInput,拿到的就是同一个文件列表?能不能把不同按钮的FileList分割开??

在苹果上使用时,上传不了视频

我自己写了个简单的上传demo是可以上传的。 用这个库上传不了,查了好久 不知道哪里出问题了。

再次确认了下 不是库导致的 是multiple导致的。当multiple为true时,无法上传视频

Object:requestOptions不知道怎么使用

@param {Object:requestOptions} [请求附加参数: formData:{},headers:{},responseType:'json',withCredentials:false]
这个参数怎么传进去呢?我试了试貌似不管用,能提供下demo吗?
我的:
requestOptions:{
headers: {
demo:'yemeishu',
Origin: 'https://wx.qq.com'
},
formData: {
webwx_data_ticket:'AQfqbTaaJaVhba7t1qqXpsno'
},
responseType:'json',
withCredentials:false
},

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.