1. 程式人生 > >vue中實現圖片丶檔案上傳

vue中實現圖片丶檔案上傳

 html頁面

 <input type="file" value=""  id="file"  @change='onUpload'>//注意不能帶括號

js程式碼

methods: {

//上傳圖片
onUpload(e){
            var formData = new FormData(); 
        f
 ormData.append('file', e.target.files[0]);
        formData.append('type', 'test');
           $.ajax({
                url: '/ShopApi/util/upload.weixun'

,//這裡是後臺介面需要換掉
                type: 'POST',
                dataType: 'json',
                cache: false,
                data: formData,
                processData: false,
                contentType: false,
                success: (res) => {                
                    if (res.code === 200) {
                        var img_tpl ='<div class="picture" style="width:108px;float:left;"><img id="preview" src="'+
後臺返回的tu'pian路徑+'" 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></div>';
                        $("#refund_img").after(img_tpl);
                    }
                },
                error: function(err) {
                alert("網路錯誤");
                }
            });
}
 

}

圖片效果圖