zoukankan      html  css  js  c++  java
  • 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')
      
  • 相关阅读:
    LeetCode 769. Max Chunks To Make Sorted
    LeetCode 845. Longest Mountain in Array
    LeetCode 1059. All Paths from Source Lead to Destination
    1129. Shortest Path with Alternating Colors
    LeetCode 785. Is Graph Bipartite?
    LeetCode 802. Find Eventual Safe States
    LeetCode 1043. Partition Array for Maximum Sum
    LeetCode 841. Keys and Rooms
    LeetCode 1061. Lexicographically Smallest Equivalent String
    LeetCode 1102. Path With Maximum Minimum Value
  • 原文地址:https://www.cnblogs.com/wuxiaoshi/p/12437141.html
Copyright © 2011-2022 走看看