這幾天做項目時涉及到一個“上傳文件”的功能實現(xiàn)璧疗,沒有用組件實現(xiàn),遇到了一些問題控轿,比如cookie權(quán)限哑蔫,接口代理,傳參等問題乍迄,特此來總結(jié)一下管引。
首先是樣式實現(xiàn)
<input type="file"
style="position:absolute;height:30px;width:100px;z-index:999;opacity:0;"
accept="image/png,image/gif,image/jpeg" onmouseover="this.style.cursor='pointer'"
@change="upFile">
<i-button type="primary" style="width:100px;">上傳文件</i-button>
因為用到了一個i-button的樣式組件,故在i-button上方寫了個隱形的input框
再是上傳文件的功能實現(xiàn)
本來沒有在api里寫接口闯两,嘗試通過下面這種方式來實現(xiàn)文件上傳褥伴。
update(e){
let file = e.target.files[0];
let param = new FormData(); //創(chuàng)建form對象
param.append('file',file);//通過append向form對象添加數(shù)據(jù)
console.log(param.get('file')); //FormData私有類對象,訪問不到漾狼,可以通過get判斷值是否傳進去
let config = {
headers:{'Content-Type':'multipart/form-data'}
}; //添加請求頭
axios.post('http://192.168.10.141:3080/Reception/SaveAttachment',param,config)
.then(response=>{
console.log(response.data);
})
}
但是這么寫我碰到了一個問題就是cookie問題重慢,后臺報錯沒有登錄無權(quán)限(但其實我登錄了)
后來通過下面的方法解決了cookie問題,先挖個坑逊躁,等我搞清楚原因后再來填坑似踱。
// 上傳文件
async upFile(e:any) {
let file = e.target.files[0];
let param = new FormData() // 創(chuàng)建form對象
param.append('file', file, file.name) // 通過append向form對象添加數(shù)據(jù)
param.append('size', file.size) // 添加form表單中其他數(shù)據(jù)
param.append('stuinfoId','606659')
console.log(param.get('file')) // FormData私有類對象,訪問不到稽煤,可以通過get判斷值是否傳進去
let res=await uploadFile(param)
}
通過
param.append('stuinfoId','606659')
實現(xiàn)向后端參數(shù)的傳遞
在api文件里調(diào)接口
export const uploadFile = (param: any): Promise<any> => {
return service.post('/Reception/SaveAttachment' , param, {headers: {'Content-Type': 'multipart/form-data'}})
}
因為本人沒有剛開始接觸項目核芽,不太了解項目結(jié)構(gòu),后來搞明白調(diào)接口的時候要再一個固定的配置文件里vue.config.js加上代理
'/Reception': {
target: 'http://192.168.10.141',
changeOrigin: true,
logLevel: 'debug'
}
好了 這樣就完成了文件的上傳酵熙。希望能夠幫到同樣有疑惑的你們~
這次要填的坑有:
1.如果自己要手動加cookie該怎么加
2.為什么寫在api文件里就可以解決cookie問題
3.后端接口是怎么識別我已經(jīng)登陸的了(同樣是cookie問題)
歡迎大家一起來填坑~~~