Home  >  Article  >  Web Front-end  >  Sample code to implement image and file upload in vue

Sample code to implement image and file upload in vue

亚连
亚连Original
2018-05-29 17:38:472992browse

Below I will share with you a sample code for uploading images and files in vue. It has a good reference value and I hope it will be helpful to everyone.

html page

<input type="file" value="" id="file" @change=&#39;onUpload&#39;>//注意不能带括号

js code

methods: {
//上传图片
onUpload(e){
      var formData = new FormData(); 
    f ormData.append(&#39;file&#39;, e.target.files[0]);
    formData.append(&#39;type&#39;, &#39;test&#39;);
      $.ajax({
        url: &#39;/ShopApi/util/upload.weixun&#39;,//这里是后台接口需要换掉
        type: &#39;POST&#39;,
        dataType: &#39;json&#39;,
        cache: false,
        data: formData,
        processData: false,
        contentType: false,
        success: (res) => {        
          if (res.code === 200) {
            var img_tpl =&#39;<p class="picture" style="width:108px;float:left;"><img id="preview" src="&#39;+后台返回的tu&#39;pian路径+&#39;" style="width:48px;height:48px;float:left;background-size:cover;"/><span class="r-span"
 onclick = "onDeletePicture()" style="color:#49BDCC;display:block;float:left;margin-left:10px;line-height:48px;">删除</span></p>&#39;;
            $("#refund_img").after(img_tpl);
          }
        },
        error: function(err) {
        alert("网络错误");
        }
      });
} 
}

Picture rendering

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

vue data control view source code analysis

A brief discussion of React high-order components

vue Sample code for developing a button component

The above is the detailed content of Sample code to implement image and file upload in vue. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn