vue如何实现图片异步上传?

一、vue-resource 是什么?

vue-resource是一个通过XMLHttpRequestJSONP技术实现异步加载服务端数据的Vue插件

二、 提供了什么方法?


三、 如何使用?

  1. 安装 vue-resource 命令: npm install vue-resource

  2. main.js 中 导入 vue-source 并作为一个组件使用

    import vueResource from 'vue-resource'
    Vue.use(vueResource)
    
  3. 如果发送网络请求 可以使用 this.$http

  4. 代码样例

    <template>
      <div>
        <input type="file" @change="getFile($event)" />
        <button @click="upload">上传</button>
        <div>{{ result }}</div>
        <div v-show="uping==1">正在上传中</div>
        <div v-show="result">
          <video ref="video" controls>您的浏览器不支持 video元素。</video>
        </div>
      </div>
    </template>
    
    <script>
    export default {
      data() {
        return {
          upath: "",
          result: "",
          uping: 0,
          baseUrl: "/api/static/upload/"
        };
      },
      methods: {
        upload: function() {
          var formdata = new FormData();
          formdata.append("file", this.upath); //filename是键,file是值,就是要传的文件
          let config = { headers: { "Content-Type": "multipart/form-data" } };
          this.uping = 1;
          this.$http
            .post("/api/app01/uploadmp4/", zipFormData, config)
            .then(function(response) {
              this.uping = 0;
              this.result = response.data;
              //绑定播放地址
              this.$refs.video.src = this.baseUrl + response.data.url;
            });
        },
        getFile: function(event) {
          this.upath = event.target.files[0];
        }
      }
    };
    </script>
    
  5. 后端代码

    def uploadmp4(request):
        if request.method == 'POST':
            item = {}
            file = request.FILES.get('file')
            f = open(os.path.join('static/upload/','',file.name),'wb')
    
            item['message'] = '上传成功'
            item['url'] = file.name
            item['error'] = 0
            #写文件 遍历文件流
            for chunk in file.chunks():
                f.write(chunk)
            return HttpResponse(json.dumps(item,ensure_ascii=False),content_type='application/json')
    
posted @ 2020-03-07 21:13  巫小诗  阅读(1011)  评论(0编辑  收藏  举报