Upload Files

You can upload File or Blob types, a Uint8Array or base64 encoded strings to upload files to Cloud Storage. For our example, we will use File type. As mentioned earlier, first we need to get a reference to the full path of the file, including the filename.

We will modify the AddTicketForm.jsx file to allow the user to upload a screenshot or an image related to the ticket.

The src/add-ticket/'AddTicketForm.jsx' file now looks like the following. The changes are highlighted in bold with comments:

import React, { Component } from 'react';
import firebase from '../firebase/firebase-config';
import { ToastSuccess, ToastDanger } from 'react-toastr-basic';

class AddTicketForm extends Component {

constructor(props) {
super(props);
this.handleSubmitEvent = this.handleSubmitEvent.bind(this);
this.handleChange = this.handleChange.bind(this);
this.onChange = this.onChange.bind(this);
console.log(props.userInfo);

this.state = {
uId: props.userId,
email: props.userInfo[0].email,
issueType: "",
department: "",
comment: "",
snapshot: null
}
}

handleChange(event) {
console.log(event.target.value);
this.setState({
[event.target.id]: event.target.value
});
}

//handle onchange - set the snapshot value to the file selected
onChange(e) {
console.log("ff ",e.target.files[0] );
this.setState({snapshot:e.target.files[0]})
}

handleSubmitEvent(e) {
e.preventDefault();
var storageRef = firebase.storage().ref();

// Create a reference to 'image'
var snapshotRef = storageRef.child('ticket_snapshots/'+this.state.snapshot.name);

//get a reference to 'this' in a variable since in callback this will point to different object
var _this = this;
snapshotRef.put(this.state.snapshot).then(function(res) {
console.log('Uploaded a blob or file!');
console.log(res.metadata);

const userId = _this.state.uId;
var data = {
date: Date(),
email: _this.state.email,
issueType: _this.state.issueType,
department: _this.state.department,
comments: _this.state.comment,
status: "progress",
snapshotURL: res.metadata.downloadURLs[0] //save url in db to use it for download
}

console.log(data);


var newTicketKey = firebase.database().ref('/helpdesk').child('tickets').push().key;
// Write the new ticket data simultaneously in the tickets list and the user's ticket list.
var updates = {};
updates['/helpdesk/tickets/' + userId + '/' + newTicketKey] = data;
updates['/helpdesk/tickets/all/' + newTicketKey] = data;

return firebase.database().ref().update(updates).then(() => {
ToastSuccess("Saved Successfully!!");
this.setState({
issueType: "",
department: "",
comment: "",
snapshot: _this.state.snapshot
});
}).catch((error) => {
ToastDanger(error.message);
});

});

//React form data object

}
//render() method - snippet given below
}
export default AddTicketForm;

Let's understand the preceding code:

  1. Add a snapshot property in the state.
  2. OnChange() - register the onChange() event for the file to set it in snapshot field in the state.
  3.   onHandleSubmit() - We have created a reference to the file to store it in a folder called 'ticket_snapshots' in Firebase Cloud storage. Once the file is uploaded successfully, we will get a download URL from response metadata, which we are storing in our realtime database along with other ticket details.

You will also do some HTML changes in the render() method to add input field for file selection:

 render() {
var style = { color: "#ffaaaa" };
return (
<form onSubmit={this.handleSubmitEvent} >
<div className="form-group">
<label htmlFor="email">Email <span style={style}>*</span></label>
<input type="text" id="email" className="form-control"
placeholder="Enter email" value={this.state.email} disabled
required onChange={this.handleChange} />
</div>
<div className="form-group">
<label htmlFor="issueType">Issue Type <span style={style}> *</span></label>
<select className="form-control" value={this.state.issueType}
id="issueType" required onChange={this.handleChange}>
<option value="">Select</option>
<option value="Access Related Issue">Access Related
Issue</option>
<option value="Email Related Issues">Email Related
Issues</option>
<option value="Hardware Request">Hardware Request</option>
<option value="Health & Safety">Health & Safety</option>
<option value="Network">Network</option>
<option value="Intranet">Intranet</option>
<option value="Other">Other</option>
</select>
</div>
<div className="form-group">
<label htmlFor="department">Assign Department
<span style={style}> *</span></label>
<select className="form-control" value={this.state.department} id="department" required onChange={this.handleChange}>
<option value="">Select</option>
<option value="Admin">Admin</option>
<option value="HR">HR</option>
<option value="IT">IT</option>
<option value="Development">Development</option>
</select>
</div>
<div className="form-group">
<label htmlFor="comments">Comments <span style={style}> *</span></label>
(<span id="maxlength"> 200 </span> characters left)
<textarea className="form-control" rows="3" id="comment" value={this.state.comment} onChange={this.handleChange} required></textarea>
</div>
<div className="form-group">
<label htmlFor="fileUpload">Snapshot</label>
<input id="snapshot" type="file" onChange={this.onChange} />
</div>
<div className="btn-group">
<button type="submit" className="btn btn-
primary">Submit</button>
<button type="reset" className="btn btn-
default">cancel</button>
</div>
</form>
);
}

Our add-ticket form looks like this:

You can then check your Firebase console to see whether file uploading is working or not. The following screenshot shows that the file (helpdesk-db.png) we have uploaded is saved successfully in Cloud Storage for Firebase:

As mentioned earlier, Cloud storage for Firebase is highly integrated with Google Cloud Storage and uses a bucket of Google Cloud Storage to store the files. You can log in to your console of Google Cloud Platform at https://console.cloud.google.com/storage and check under the storage section. You should see all your uploaded files there also.

The next screenshot shows that the files can be viewed from Google Cloud Platform console:

Now, you can check your database also to see whether the ticket that has been created has snapshot URL property and corresponding value—downloadURL of the file.

The following screenshot of the database shows that the snapshot URL is getting stored correctly:

Yay! The Cloud Storage is integrated with our application. However, we are not done yet. We will need to allow the user to see the uploaded images, so we will implement a download file functionality too. However, before we move to download file function, I would like to mention that you should update the security rules for Cloud Storage to control access to your files. As per default rules, Firebase Authentication is required in order to perform any .read and .write operations on all files.

The default rules look like the following image:

However, you should update them as per your requirement.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset