editor-js / attaches

File attachments Block for the Editor.js
MIT License
64 stars 66 forks source link

Custom upload function #5

Closed hasufell closed 2 years ago

hasufell commented 4 years ago

editor-js/image provides a uploadByFile function. I think simply an endpoint is not enough for attaches either. E.g. I have to pass CSRF-token and do other stuff.

shoks commented 4 years ago

think the same a custom upload and a header append. i was obligated to extend the plugin class

chikwesi commented 4 years ago

hello shoks, i have the same issue. i want to set a custom header. can i see how you extended the plugin class

shoks commented 4 years ago

a bit late but:

index.js

import Uploader from './uploader';

import BaseAttachesToolBase from '@editorjs/attaches';

export default class AttachesTool extends BaseAttachesToolBase{
    /**
     * @param {AttachesToolData} data
     * @param {Object} config
     * @param {API} api
     */
    constructor({ data, config, api }) {
        super({ data: data, config: config, api: api });

        super.uploader = new Uploader({
            config: config,
            onUpload: (response) => super.onUpload(response),
            onError: (error) => super.uploadingFailed(error)
        });
    }
}

uploader.js

import ajax from '@codexteam/ajax';

/**
 * Module for file uploading.
 */
export default class Uploader {
    /**
     * @param {Object} config
     * @param {function} onUpload - callback for successful file upload
     * @param {function} onError - callback for uploading errors
     */
    constructor({config, onUpload, onError}) {
        this.config = config;
        this.onUpload = onUpload;
        this.onError = onError;
    }

    /**
     * Handle clicks on the upload file button
     * @fires ajax.transport()
     * @param {function} onPreview - callback fired when preview is ready
     */
    uploadSelectedFile({onPreview}) {
        ajax.transport({
            url: this.config.endpoint || '',
            accept: this.config.types || '*',
            data: this.config.additionalRequestData || {},
            headers: this.config.additionalRequestHeaders || {},
            beforeSend: () => onPreview(),
            fieldName: this.config.field || 'file'
        }).then((response) => {
            this.onUpload(response);
        }).catch((error) => {
            const message = (error && error.message) ? error.message : this.config.errorMessage || 'File upload failed';

            this.onError(message);
        });
    }
}
atulmy commented 3 years ago

Option to have custom upload function similar to editor-js/image would be very useful.

thekhegay commented 3 years ago

Any updates?

NogaMan commented 3 years ago

That would be very useful!

Sometimes it is hard to poke back-enders with a stick to add yet another endpoint just to wrap the response with another JSON format.

cleverplatypus commented 3 years ago

Hi! As the authors don't seem to be very reactive on the subject, I forked this repo and added the custom uploader functionality that conforms to the @editorjs/image configuration.

I'm currently using it in conjunction with Firebase Storage APIs and it seems to work fine.

https://github.com/cleverplatypus/attaches

Docs are quite straightforward and you'll find them at the bottom of README.md

Feel free to use/enquiry.

Cheers! image

kfanslerforaye commented 3 years ago

Hi! As the authors don't seem to be very reactive on the subject, I forked this repo and added the custom uploader functionality that conforms to the @editorjs/image configuration.

I'm currently using it in conjunction with Firebase Storage APIs and it seems to work fine.

https://github.com/cleverplatypus/attaches

Docs are quite straightforward and you'll find them at the bottom of README.md

Feel free to use/enquiry.

Cheers! image

cleverplatypus, This is a great addition, thank you for taking time to implement. Apologize in advance if not proper process for asking questions as new to leveraging github for open source projects. Is your custom upload function now included in "attaches" (is it included here: https://cdn.jsdelivr.net/npm/@editorjs/attaches@latest)? When I try to use, I get a failure to upload file.

POST http://127.0.0.1:5500/addCard.html 405 (Method Not Allowed)

I am not sure if I get this error simply because I dont have your changes. If your changes are not in the main branch yet, is it possible to run your branch (and if so, wouldn't I need to point to a different CDN than the primary)?

I am using Firebase Storage so not really sure how to do with a URL instead of using a function. On code side, I also saw an implementing is the file:File which gives me an error of Type annotations can only be used in TypeScript files. I implemented this code which is similar to my Image upload to Firebase storage. Note, I hardcoded size and name temporarily while I work to resolve issue.


attaches: {
            class: AttachesTool,
            config: {
              uploader: {
                uploadByFile : async (file) => {
                    try{
                        let storageRef = firebase.storage().ref();
                        let fileRef = storageRef.child('EditorJS').child('attachments/'+ file.name);
                        let metadata = {
                            contentType: 'application/pdf'
                        };
                        let uploadTask = await fileRef.put(file, metadata);
                        const downloadURL = await uploadTask.ref.getDownloadURL();
                        const name = 'abc';
                        const size = '500';
                        return {
                            success : true,
                            file : {
                            url : downloadURL,
                            name : name,
                            size : size
                            }
                        };
                    } catch (e) {
                        return Promise.reject({error : e.message});
                    }
                }
            }
          }
        }
cleverplatypus commented 3 years ago

Hi @kfanslerforaye.

My changes are not in NPM/Yarn. They're in my public fork here https://github.com/cleverplatypus/attaches

I created a pull request here https://github.com/editor-js/attaches/pull/31

You should be able to resolve the conflicts quickly and merge the changes.

Cheers

neSpecc commented 2 years ago

Resolved