美文网首页
ajax请求上传图片文件

ajax请求上传图片文件

作者: 九毛Evaline | 来源:发表于2017-12-27 14:43 被阅读0次

用axios实现上传图片和文件功能 , 首先html页面 :

<input type='text' v-moudel='username' />

<input type='file' id='file' />

<button @click='upload'>上传</button>

一个text输入框 , 一个文件输入框

js : 

upload: function() {

      var data = new FormData();

      data.append('username', this.username);

      data.append('img', document.getElementById('file').files[0]);        //因为传入的文件可能有很多 , 一个一个传输

      var config = {        // 这个函数是表示进度的 ,  在这里打印 percentCompleted ( 0-100 ) , 可以根据他的值做进度条

        onUploadProgress: function(progressEvent) { 

          var percentCompleted = Math.round( (progressEvent.loaded * 100) / progressEvent.total );

          console.log(percentCompleted);

        }  

      };

      axios.post('/upload/server', data, config)        //提交 不能用get请求

        .then(function (res) {

          console.log(res);

        })

        .catch(function (err) {        // catch 错误并打印

          console.log(err);

        });

    }

  }

第二种方法不是用ajax , 是用表单仿的 ajax , 缺点是没办法做进度条 , 是比较老的方法 , 但是写起来比较简单

<form target=' fakeajax ' method=' post ' enctype=' multipart/form-data ' action=" http://localhost:3000/upload/server " >

    <input type = "text" name = "username" />

    <input type = 'file' name = "username" />

    <button type=' submit '>上传</button>

    <iframe id=' fakeajax ' name = " fakeajax " style = " display:none " ></iframe>

</form>

相关文章

网友评论

      本文标题:ajax请求上传图片文件

      本文链接:https://www.haomeiwen.com/subject/egfugxtx.html