使用axios上传照片
原來(lái)使用vue1.0的時(shí)候,我們一直使用ajax來(lái)發(fā)送請(qǐng)求,當(dāng)接觸新的項(xiàng)目的時(shí)候,我們使用了vue2.0,結(jié)合著使用了axios來(lái)代替ajax。
安裝axios的話:
1-利用npm安裝npm install axios --save
2、 利用bower安裝bower install axios --save
3、 直接利用cdn引入
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>4-或者使用ES6的寫(xiě)法引入
import axios from 'axios'使用的話可以參考這篇文章:http://www.jianshu.com/p/df464b26ae58
這里我只講一下,如何使用axios上傳照片:
一般情況上傳照片有兩種方式:
1.本地圖片轉(zhuǎn)換成base64,然后通過(guò)普通的post請(qǐng)求發(fā)送到服務(wù)端。
操作簡(jiǎn)單,適合小圖,以及如果想兼容低版本的ie沒(méi)辦法用此方法
2.通過(guò)form表單提交。
form表單提交圖片會(huì)刷新頁(yè)面,也可以時(shí)form綁定到一個(gè)隱藏的iframe上,可以實(shí)現(xiàn)無(wú)刷新提交數(shù)據(jù)。
這里只講解一下第二種方式:
HTML代碼:
<input name="file" type="file" accept="image/png,image/gif,image/jpeg" @change="update"/>JS代碼:
import axios from 'axios'// 添加請(qǐng)求頭 update (e) { // 上傳照片var self = thislet file = e.target.files[0]/* eslint-disable no-undef */let param = new FormData() // 創(chuàng)建form對(duì)象param.append('file', file, file.name) // 通過(guò)append向form對(duì)象添加數(shù)據(jù)param.append('chunk', '0') // 添加form表單中其他數(shù)據(jù)console.log(param.get('file')) // FormData私有類(lèi)對(duì)象,訪問(wèn)不到,可以通過(guò)get判斷值是否傳進(jìn)去let config = {headers: {'Content-Type': 'multipart/form-data'}}// 添加請(qǐng)求頭axios.post('http://172.19.26.60:8081/rest/user/headurl', param, config).then(response => {if (response.data.code === 0) {self.ImgUrl = response.data.data}console.log(response.data)})} /* http://172.19.26.60:8081/rest/user/headurl這里是你的服務(wù)器接口地址 */其實(shí)你可以先在postman中進(jìn)行測(cè)試
這里注意的是,設(shè)置 Content-Type
下面附加一個(gè)完整的單個(gè)實(shí)例:
<html><head><title>mayouchen</title></head><script src="https://cdn.bootcss.com/axios/0.16.2/axios.min.js"></script><script type="text/javascript">function uploadpic(e){var self = thisconsole.log(e.target);let file = e.target.files[0]/* eslint-disable no-undef */let param = new FormData() // 創(chuàng)建form對(duì)象param.append('file', file, file.name) // 通過(guò)append向form對(duì)象添加數(shù)據(jù)param.append('chunk', '0') // 添加form表單中其他數(shù)據(jù)console.log("222222");console.log(param.get('file')) // FormData私有類(lèi)對(duì)象,訪問(wèn)不到,可以通過(guò)get判斷值是否傳進(jìn)去let config = {headers: {'Content-Type': 'multipart/form-data'}}// 添加請(qǐng)求頭axios.post('http://xingchen.mengdian.com/rest/user/headurl', param, config).then(response => {console.log("222222");if (response.data.code === 0) {console.log(response.data.data);}console.log(response.data)})}</script><body><div class='form-div'><div class="up-pic"><input name="file" type="file" accept="image/png,image/gif,image/jpeg" onclick="uploadpic(event)"/></div></div></body> </html>總結(jié)
以上是生活随笔為你收集整理的使用axios上传照片的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 斐讯p.to怎么恢复出厂设置-斐讯路由器
- 下一篇: 路由器限速技巧与网速影响 如何路由器网速