我正在尝试将文件上传到Firebase,如下所示:
uploadImage(file) {
// Create the file metadata
var metadata = {
contentType: 'image/jpeg'
};
console.log(1);
try {
var uploadTask = firebase.storage().ref().child('images/' + file.name).put(file, metadata);
} catch (e) {
console.log('tutej', e)
}
// Upload file and metadata to the object 'images/mountains.jpg'
console.log(2);
// Listen for state changes, errors, and completion of the upload.
uploadTask.on(firebase.storage.TaskEvent.STATE_CHANGED, // or 'state_changed'
function (snapshot) {
console.log(3);
// Get task progress, including the number of bytes uploaded and the total number of bytes to be uploaded
var progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
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;
default:
console.log('test1');
break;
}
}, function (error) {
console.log(4);
// A full list of error codes is available at
// https://firebase.google.com/docs/storage/web/handle-errors
switch (error.code) {
case 'storage/unauthorized':
// User doesn't have permission to access the object
break;
case 'storage/canceled':
// User canceled the upload
break;
case 'storage/unknown':
// Unknown error occurred, inspect error.serverResponse
break;
default:
console.log('test2');
break;
}
}, function () {
console.log(4);
// Upload completed successfully, now we can get the download URL
uploadTask.snapshot.ref.getDownloadURL().then(function (downloadURL) {
console.log('File available at', downloadURL);
});
});
}
HTML:
<form encType="multipart/form-data" onSubmit={this.handleSubmit}>
<textarea name="textAnswer" id="textAnswer" style={{
width: '100%',
height: '50vh',
background: 'white',
color: 'black'
}}/>
<input id="fileAnswer" type="file" size='10000000'/>
<Button type='submit' style={{display: 'block'}}>Wyslij odpowiedz</Button>
<Button onClick={this.handleClick} style={{display: 'block'}}>Anuluj rozwiazywanie</Button>
</form>
函数调用:
var fileAnswer = document.getElementById('fileAnswer').value;
if (fileAnswer.length > 0) {
this.uploadImage(fileAnswer);
}
它应该如何工作:我希望将上传了HTML <input>
元素的文件作为图片上传到Firebase。到目前为止,当我尝试这样做时,我得到了这个:
error = {
code_: "storage/invalid-argument",
message_: "Firebase Storage: Invalid argument in `put` at index 0: Expected Blob or File.",
name_: "FirebaseError",
serverResponse_: null ,
};
根据我的研究,我需要将其变成Blob
。但为什么? <input>
字段的值不是文件吗?它看起来像文件的路径。 (例如:C:\fakepath\8a25f4e0b058f2ce8480ef3741823762.png
)
那么有什么区别,如何将其作为文件?
总之?我需要做些什么来实际上传它,以及为什么使用<input>
还不够?