UploadPhoto component handles the photo upload request to the Klaytn blockchain. The process is as follows:
Invoke uploadPhoto method of the smart contract by sending a transaction. Inside the uploadPhoto contract method, a new ERC-721 token is minted.
After sending a transaction, show the progress along the transaction life cycle using the Toast component.
When the transaction gets into a block, update the new PhotoData in the local redux store.
Limiting content size
The maximum size of a single transaction is 32KB. So we restrict the input data (photo and descriptions) not to exceed 30KB to send it over safely.
The string data size is restricted to 2KB
Photo is compressed to be less than 28KB using imageCompression() function.
2) Component code
// src/components/UploadPhoto.jsimport React, { Component } from'react'import { connect } from'react-redux'import imageCompression from'utils/imageCompression';import ui from'utils/ui'import Input from'components/Input'import InputFile from'components/InputFile'import Textarea from'components/Textarea'import Button from'components/Button'import*as photoActions from'redux/actions/photos'import'./UploadPhoto.scss'// Set a limit of contentsconstMAX_IMAGE_SIZE=30*1024// 30KBconstMAX_IMAGE_SIZE_MB=30/1024// 30KBclassUploadPhotoextendsComponent { state = { file:'', fileName:'', location:'', caption:'', warningMessage:'', isCompressing:false, }handleInputChange= (e) => {this.setState({ [e.target.name]:e.target.value, }) }handleFileChange= (e) => {constfile=e.target.files[0]/** * If image size is bigger than MAX_IMAGE_SIZE(30KB), * Compress the image to load it on transaction * cf. Maximum transaction input data size: 32KB */if (file.size >MAX_IMAGE_SIZE) {this.setState({ isCompressing:true, })returnthis.compressImage(file) }returnthis.setState({ file, fileName:file.name, }) }handleSubmit= (e) => {e.preventDefault()const { file,fileName,location,caption } =this.statethis.props.uploadPhoto(file, fileName, location, caption)ui.hideModal() }compressImage=async (imageFile) => {try {constcompressedFile=awaitimageCompression(imageFile,MAX_IMAGE_SIZE_MB)this.setState({ isCompressing:false, file: compressedFile, fileName:compressedFile.name, }) } catch (error) {this.setState({ isCompressing:false, warningMessage:'* Fail to compress image' }) } }render() {const { fileName,location,caption,isCompressing,warningMessage } =this.statereturn ( <formclassName="UploadPhoto"onSubmit={this.handleSubmit}> <InputFileclassName="UploadPhoto__file"name="file"label="Search file"fileName={isCompressing ?'Compressing image...': fileName}onChange={this.handleFileChange}err={warningMessage}accept=".png, .jpg, .jpeg"required /> <InputclassName="UploadPhoto__location"name="location"label="Location"value={location}onChange={this.handleInputChange}placeholder="Where did you take this photo?"required /> <TextareaclassName="UploadPhoto__caption"name="caption"value={caption}label="Caption"onChange={this.handleInputChange}placeholder="Upload your memories"required /> <ButtonclassName="UploadPhoto__upload"type="submit"title="Upload" /> </form> ) }}constmapDispatchToProps= (dispatch) => ({uploadPhoto: (file, fileName, location, caption) =>dispatch(photoActions.uploadPhoto(file, fileName, location, caption)),})exportdefaultconnect(null, mapDispatchToProps)(UploadPhoto)
3) Interact with contract
Let's make a function to write photo data on Klaytn. Send transaction to contract: uploadPhoto
Unlike read-only function calls, writing data incurs a transaction fee. The transaction fee is determined by the amount of used gas. gas is a measuring unit representing how much calculation is needed to process the transaction.
For these reasons, sending a transaction needs two property from and gas.
Convert photo file as a bytes string to load on transaction
Read photo data as an ArrayBuffer using FileReader
Convert ArrayBuffer to hex string
Add Prefix 0x to satisfy bytes format
Invoke the contract method: uploadPhoto
from: An account that sends this transaction and pays the transaction fee.
gas: The maximum amount of gas that the from account is willing to pay for this transaction.
After sending the transaction, show progress along the transaction lifecycle using Toast component.
If the transaction successfully gets into a block, call updateFeed function to add the new photo into the feed page.
// src/redux/actions/photo.jsexportconstuploadPhoto= ( file, fileName, location, caption) => (dispatch) => {// 1. Convert photo file as a hex string to load on transactionconstreader=newwindow.FileReader()reader.readAsArrayBuffer(file)reader.onloadend= () => {constbuffer=Buffer.from(reader.result)// Add prefix `0x` to hexString to recognize hexString as bytes by contractconsthexString="0x"+buffer.toString('hex')// 2. Invoke the contract method: uploadPhoto// Send transaction with photo file(hexString) and descriptionstry{KlaystagramContract.methods.uploadPhoto(hexString, fileName, location, caption).send({ from:getWallet().address, gas:'200000000', }, (error, txHash) => {if (error) throw error;// 3. After sending the transaction,// show progress along the transaction lifecycle using `Toast` component.ui.showToast({ status:'pending', message:`Sending a transaction... (uploadPhoto)`, txHash, }) }).then((receipt) => {ui.showToast({ status:receipt.status ?'success':'fail', message:`Received receipt! It means your transaction is in klaytn block (#${receipt.blockNumber}) (uploadPhoto)`, link:receipt.transactionHash, })// 4. If the transaction successfully gets into a block,// call `updateFeed` function to add the new photo into the feed page.if(receipt.status) {consttokenId=receipt.events.PhotoUploaded.returnValues[0]dispatch(updateFeed(tokenId)) } }) } catch (error) {ui.showToast({ status:'error', message:error.toString(), }) } }}
cf) Transaction life cycle
After sending transaction, you can get transaction life cycle (transactionHash, receipt, error).
transactionHash event is fired once your signed transaction instance is properly constructed. You can get the transaction hash before sending the transaction over the network.
receipt event is fired when you get a transaction receipt. It means your transaction is included in a block. You can check the block number by receipt.blockNumber.
error event is fired when something goes wrong.
4. Update photo in the feed page: updateFeed
After successfully sending the transaction to the contract, FeedPage needs to be updated.
In order to update the photo feed, we need to get the new photo data we've just uploaded. Let's call getPhoto() with tokenId. tokenId can be retrieved from the transaction receipt. Then add the new photo data in the local redux store.
// src/redux/actions/photo.js/** * 1. Call contract method: getPhoto() * To get new photo data we've just uploaded, * call `getPhoto()` with tokenId from receipt after sending transaction*/constupdateFeed= (tokenId) => (dispatch, getState) => {KlaystagramContract.methods.getPhoto(tokenId).call().then((newPhoto) => {const { photos: { feed } } =getState()constnewFeed= [feedParser(newPhoto),...feed]// 2. update new feed to storedispatch(setFeed(newFeed)) })}