前后端交互圖片文件
上傳-圖片
注意1:上傳的圖片必須在2MB以內(nèi)
注意2:服務(wù)器端oss(阿里云對象存儲)為了安全性,圖片url網(wǎng)址不能直接在瀏覽器地址欄訪問
請用img/背景圖方式進(jìn)行使用
上傳圖片的代碼實(shí)現(xiàn)
\* 目標(biāo):圖片上傳,顯示到網(wǎng)頁上
* 1. 獲取圖片文件
* 2. 使用 FormData 攜帶圖片文件文章來源:http://www.zghlxwxcb.cn/news/detail-634055.html
* 3. 提交到服務(wù)器,獲取圖片url網(wǎng)址使用文章來源地址http://www.zghlxwxcb.cn/news/detail-634055.html
// 1.獲取選擇文件按鈕,同時注冊一個變化事件
document.querySelector('.upload').addEventListener('change', e => {
console.log(e.target.files[0])
// 2. 使用 FormData 構(gòu)造函數(shù) 攜帶圖片文件夾
const imgs = new FormData()
// 調(diào)用實(shí)例對象中 append 方法,傳入圖片
imgs.append('img',e.target.files[0])
// 3. 提交到服務(wù)器,獲取圖片url網(wǎng)址使用
axios({
url: 'http://hmajax.itheima.net/api/uploadimg',
method: 'POST',
data: imgs
}).then(result => {
console.log(result.data.data)
const imgUrl = result.data.data.url
document.querySelector('.my-img').src = imgUrl
})
})
網(wǎng)站背景更換
- 目標(biāo):網(wǎng)站-更換背景
-
- 選擇圖片上傳,設(shè)置body背景
-
- 上傳成功時,"保存"圖片url網(wǎng)址
-
- 網(wǎng)頁運(yùn)行后,"獲取"url網(wǎng)址使用
- 在上傳圖片的基礎(chǔ)上增加了存儲到本地的功能需求,同時沒有url返回,不執(zhí)行更換背景。
//1、選擇圖片上傳,給body設(shè)置背景圖片
// 1.2 獲取按鈕進(jìn)行上傳
document.querySelector('.bg-ipt').addEventListener('change', e => {
console.log(e.target.files[0])
// 表單事件對象
const fd = new FormData()
fd.append('img' , e.target.files[0])
axios({
url: 'http://hmajax.itheima.net/api/uploadimg',
method: 'POST',
data: fd
}).then(result => {
const res = result.data.data.url
// 更換body的背景圖
document.body.style.backgroundImage = `url(${res})`
// 2、上傳成功時,"保存"圖片url網(wǎng)址 到本地,防止刷新丟失
localStorage.setItem('bgImg',res)
})
})
// 3. 網(wǎng)頁運(yùn)行后,"獲取"url網(wǎng)址使用
const bgUrl = localStorage.getItem('bgImg')
console.log(bgUrl)
// 邏輯與中斷,本地有服務(wù)器提交后的url的話,那么就執(zhí)行后面的,否則為空值不執(zhí)行
bgUrl && (document.body.style.backgroundImage = `url(${bgUrl})`)
到了這里,關(guān)于(前后端交互式)Ajax上傳圖片 + 更換背景圖片的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!