Skip to content
This repository has been archived by the owner on Dec 31, 2024. It is now read-only.

Commit

Permalink
Upload to ipfs via backend
Browse files Browse the repository at this point in the history
  • Loading branch information
aminlatifi committed Mar 30, 2022
1 parent bbfb3ea commit 2dfcc94
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 16 deletions.
3 changes: 0 additions & 3 deletions src/components/UploadPicture.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,6 @@ const UploadPicture = ({ picture, setPicture, imgAlt, disabled, aspectRatio, lab
},
onChange(info) {
const { status } = info.file;
if (status !== 'uploading') {
console.log(info.file, info.fileList);
}
if (status === 'done') {
console.log('file uploaded successfully.', info.file.response);
setPicture(info.file.response);
Expand Down
27 changes: 14 additions & 13 deletions src/services/IPFSService.js
Original file line number Diff line number Diff line change
@@ -1,42 +1,43 @@
import config from '../configuration';
import ImageTools from '../lib/ImageResizer';
import ErrorPopup from '../components/ErrorPopup';
import { feathersClient } from '../lib/feathersClient';

class IPFSService {
/**
* Upload a json object or Blob to ipfs
*
* @param {object|Blob|string} obj Object/Blob to upload to ipfsGateway. The only valid string is a base64 encoded image.
*/
static upload(obj) {
static async upload(obj) {
const { ipfsGateway } = config;
if (!ipfsGateway || ipfsGateway === '') {
console.log('not uploading to ipfs. missing ipfsGateway url');
return Promise.resolve();
}

let body;
if (typeof obj === 'string') {
if (obj.match(/^\/ipfs\/[^/]+$/) !== null) {
return Promise.resolve(obj);
}
if (!ImageTools.isImage(obj)) {
throw new Error('Cant upload string to ipfs');
}
body = ImageTools.toBlob(obj);
} else {
body =
obj instanceof Blob ? obj : new Blob([JSON.stringify(obj)], { type: 'application/json' });
}

return fetch(`${ipfsGateway}`, {
method: 'POST',
body,
}).then(res => {
if (res.ok) return `/ipfs/${res.headers.get('Ipfs-Hash')}`;
ErrorPopup('Something went wrong with the upload.', 'IPFS upload unsuccessful');
throw new Error('IPFS upload unsuccessful', res);
const reader = new FileReader();
reader.readAsDataURL(obj);
await new Promise(resolve => {
reader.onloadend = resolve;
});

try {
const result = await feathersClient.service('uploads').create({ uri: reader.result });
return result;
} catch (e) {
ErrorPopup('Something went wrong with the upload.', 'Upload unsuccessful');
throw new Error('IPFS upload unsuccessful', e);
}
}
}

Expand Down

0 comments on commit 2dfcc94

Please sign in to comment.