반응형
VueJs 앱에서 Firebase로 이미지 업로드
사용자가 동일한 이벤트에서 등록하고 이미지를 업로드할 수 있도록 해 이름, 이메일 등 데이터가 소방서에 가고 이미지가 저장 버킷에 가게 되는데, 현재는 이 두 가지 기능을 구현할 수 있지만, 별개로 내가 조금 고착되어 있는 것은 데이터와 이미지를 어떻게 연결해서 다시 업로드할 수 있는가 하는 것이다.나중에 그것들을 얻는다.나는 또한 Vuex를 사용하여 이것을 하고 싶다. 아래 코드는 내가 나의 .vue 컴포넌트로부터 데이터와 이미지를 각각 소방서와 저장소로 보내는 방법을 설명한다.
import { storage } from '../firebase/init.js'
import firebase from 'firebase'
export default {
data(){
return {
email: '',
password: '',
image: null
}
},
methods: {
signUp(){
firebase.auth().createUserWithEmailAndPassword(this.email, this.password)
.then(response => {
let user = {
id: response.user.id,
email: response.user.email
}
//here i want to do something to link this user to the upload image event below
})
},
uploadFile(e){
const file = e.target.files[0];
storage.ref('images/'+ file.name).put(file)
.then(response => {
console.log(response)
})
.catch(err => console.log(err))
}
}
추가 설명을 위해 아래에 코멘트를 남겨 두십시오. 미리 감사하십시오.
당신은 이미지의 URL을 반환하고 그것을 당신의 데이터베이스에 입력하기 위해 소방서를 구해야 한다.다음과 같은 방법을 사용해 보십시오.
uploadFile(e){
const file = e.target.files[0];
storage.ref('images/'+ file.name).put(file)
.then(response => {
response.ref.getDownloadURL().then((downloadURL) => {
firebase.database().ref(YOUR_DATABASE).child(THE_USER_ID).update({imageUrl:downloadURL})
}
.catch(err => console.log(err))
}
그러면 데이터베이스에 이미지 URL을 삽입하고 모든 사용자 데이터를 호출할 때 이 URL을 호출할 수 있다.
createNewProperty({commit, getters, state}, payload) {
commit('setLoading', true)
const newService = {
name : payload.name,
PropertyMap: payload.PropertyMap,
location : payload.Location,
AboutProperty: payload.AboutProperty
}
var dropName = ''
//Check If Service Exists
firebase.firestore().collection('CompanyMenu')
.where('name','==',payload.name)
.where('location','==',payload.Location)
.get()
.then(service=>{
if(service.size == 0) {
let key
let imageUrl
firebase.firestore().collection('properties')
.add(newService)
.then( (data)=>{
key = data.id
return key
}).then(key=>{
const filename = payload.Image.name
const ext = filename.slice(filename.lastIndexOf('.'))
dropName = key +'.'+ext
var uploadTask = firebase.storage().ref('properties/'+ key +'.'+ext).put(payload.Image)
uploadTask.on(firebase.storage.TaskEvent.STATE_CHANGED,
function(snapshot) {
var progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
commit('setUploading', progress)
console.log('Upload is ' + progress + '% done');
switch (snapshot.state) {
case firebase.storage.TaskState.PAUSED: // or 'paused'
console.log('Upload is paused');
break;
case firebase.storage.TaskState.RUNNING: // or 'running'
console.log('Upload is running');
break;
}
},function(error) {
switch (error.code) {
case 'storage/unauthorized':
console.log('User doesn\'t have permission to access the object')
break;
case 'storage/canceled':
console.log('User canceled the upload')
break;
case 'storage/unknown':
console.log('Unknown error occurred, inspect error.serverResponse')
break;
}
},
function() {
uploadTask.snapshot.ref.getDownloadURL().then(function(downloadURL) {
console.log('File available at', downloadURL);
firebase.firestore().collection('properties').doc(key).update({Image: downloadURL,filename: dropName})
.then( (company)=>{
state.properties.push({
id: key,
Image: downloadURL,
filename: dropName,
...newService
})
commit('setLoading', false)
this.$router.push('/Properties')
} )
})
})
})
} else {//If Service Exists
}
})
}
이 코드는 나에게 가장 잘 맞는다.Firebase 스토리지에서 파일을 삭제하고자 하는 링크도 추가했다.
참조URL: https://stackoverflow.com/questions/53026245/uploading-images-to-firebase-from-vuejs-app
반응형
'programing' 카테고리의 다른 글
vueJS 변환 회전 스타일 인라인 (0) | 2022.04.12 |
---|---|
Vue 3의 템플릿 렌더 대 렌더 함수 h() (0) | 2022.04.12 |
VueX 상태에서 값을 직접 설정하는 방법 (0) | 2022.04.12 |
Azure Web App에서 Vue Router HTML5 History 모드를 사용한 URL 재작성 문제 (0) | 2022.04.12 |
vuejs 차트j에 json 데이터 표시 (0) | 2022.04.12 |