Coder Social home page Coder Social logo

rovak / inlineattachment Goto Github PK

View Code? Open in Web Editor NEW
616.0 28.0 77.0 380 KB

Easily paste and upload files/images in plain textareas

Home Page: http://git.razko.nl/InlineAttachment

License: MIT License

JavaScript 96.91% HTML 3.09%
clipboard textarea bower npm javascript

inlineattachment's Introduction

A new version is being developed in the dev-3.x branch

Inline Attachment 2.0.3 Master Branch Build Status

Adds upload functionality to a textarea or CodeMirror instance by either drag-dropping or pasting (only in chrome) an image inside it.

It's similar to pasting of images in Github.

demo

Getting started

The latest versions are available here

Bower

The package can be installed using Bower

bower install inline-attachment

Documentation

Documentation can be found on ReadTheDocs

Handling image uploads

The Demo folder contains an example in PHP on how to handle uploads.

Build

To build the project you need node, npm and grunt installed. These tools can be installed on Ubuntu as follows:

Follow the Node.js guide: Node.js installation

Go to the project folder and run the following:

npm install
grunt

This should build the project and the files will appear in the dist/ folder

Changelog

See Github releases

inlineattachment's People

Contributors

abrom avatar choonkeat avatar fcsonline avatar goruha avatar ikonitas avatar kossnocorp avatar romb avatar rovak avatar snack-x avatar wdoekes avatar y-chiasson avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

inlineattachment's Issues

Saving with attached file name

Which method should to use for same filename output and stored for e.g filename is "test.jpg" but after uploading it's change to "image-1388234246756.jpg". How should i resolved this.

CodeMirror 3

Check compatibility with CodeMirror 3 and add new version if necessary

Test captures not providing any utility?

Running the CasperJS task grunt casperjs generates some screen captures in the ./capture directory, but they all appear to be the same:

step-1
step-2
step-3
step-4

Is this currently the expected behavior?

CodeMirror 4

inlineAttachment stopped working when upgrading to 4.3.

I replaced the block on L51 with:

codeMirror.on('drop', function(data, e) {
  e.stopPropagation();
  e.preventDefault();
  return inlineattach.onDrop(e);
});

I'm not sure if this is backwards compatible with CodeMirror < 4, or how you would best distinguish which method to use (setOption or on)

Just wanted to present my findings should anyone else be in this situation.

Better hook system

Right now the hooks are being overruled by the library specific code, example 1 example 2

It must be able to hook into these events using the options parameter, for example it should be able to show a thumbnail after a successful upload action.

Error handling

I'm considering adding an error callback to react if the file wasn't uploaded correctly.

I believe this should be overridable. Do you have any ideas about this, or would you like me to send a PR with it?

Binded File Input Support

In github comment box, you have the option to drag/drop, paste or select file/images. This plugin lacks the "select" using file input.

I achieved this by directly modifying a dist js (jquery version) by adding the option bindedFileInput. This should trigger the upload when change event occurs on the input element. I'm not that familiar with grunt/npm and don't have the time implement a build so if your kind enough to add this bits of code for me that would be awesome.

init (jquery)

if (typeof options.bindedFileInput != 'undefined') {
  var $input = typeof options.bindedFileInput === 'string' ? $(options.bindedFileInput) : options.bindedFileInput;
  $input.bind('change', function(e) {
    inlineattach.onBindedFileInputChange(e.originalEvent);
  });
}

inside class definition

 /**
 * called on bindedFileInput change event occured
 * @param {Event} e
 * @return {Boolean} if the event was handled
 */
inlineAttachment.prototype.onBindedFileInputChange = function(e) {
  var result = false,
    files = e.target.files || [];

  for (var i = 0; i < files.length; i++) {
    var file = files[i];
    if (this.isFileAllowed(file)) {
      result = true;
      this.onFileInserted(file);
      this.uploadFile(file);
    }
  }

  if (result) { e.preventDefault(); }

  return result;
}

add the option to defaults

/**
 * Binded File Input element to trigger uploaded when changed
 */
bindedFileInput: undefined,

great plugin btw.

Add ProseMirror example

I'd love an example of how to make InlineAttachment work with ProseMirror.

Specifically I'd like to see how to make it work with the 'Markdown' editing mode of this ProseMirror example: http://prosemirror.net/demo_markdown.html

(Many thanks for your work on this - very useful, sorry my JS isn't good enough to work out the best way to make it work with ProseMirror)

Internet Explorer 10

The latest Internet Explorer which is still in beta seems to support drag & drop events. Ignore the paste event for now.

Problem to get the relevant Instance, Saving the instance

Hello,

first of all, i would like to thank you for that very good project. That project could take many work off hand :)

I have a special question.

I have a big problem with your lib in combination with the jQ Sortable.

Especially, I have a two layered..

@Attach "One" you can see an overview about the project.

It is a collection of looks.

The unique Looks have a lookposition starting by 1 to N-Numbers of Looks. A new Look can be added by Click to "First" or "Last".

One Look Container will be added by using this function:

function addClonedLookRow(pos) {

    var counter = 0;
    var $container = $('.sortable_looks');
    var $cloneObj = $('.overContent').filter('.clone');

    var $clone = $cloneObj.clone();
        $clone.removeClass('clone');
        $clone.addClass('new');
        $clone.attr('rel', '');

        $clone.find('.imgContainer[modulformat="'+currentInlineUploadMethod+'"]').show();

    if(pos == 'First') { 

        var tmp = {0:1};

        $.each(gl_countLookArticles, function(i,val){

            tmp[parseInt(i)+1] = val;

        }); 
        counter = 1;
        gl_countLookArticles = tmp;

    } else {

        for (i in gl_countLookArticles){counter++;}

        gl_countLookArticles[counter] = 1;

    }


    $clone.show();
    $clone.attr('lookpos',counter);

    if(pos == 'First') {

        $clone.insertBefore($container.children().first());

    } else {

        $clone.appendTo($container);
    }

    attachInlineUploadByLookPos(counter);
    reindexLookPos();

}

The variable "gl_countLookArticles" is a global Variable which contains all existing Looks and the count of articles to each look.

The function attachInlineUploadByLookPos:

function attachInlineUploadByLookPos(lookpos) {

    console.log('Given lookpos:'+lookpos);

    $.each(
        [$(".overContent[lookpos='"+lookpos+"'] .OCone .imgContainer[modulformat='full']") ,
         $(".overContent[lookpos='"+lookpos+"'] .OCone .imgContainer[modulformat='half']")], 
        function(i,val){

            $(val).inlineattach({
                customUploadHandler: c_onReceivedFile,
                uploadUrl: 'index.php?action=DELETED&method=saveInlineImgUpload&s='+$sess,
                uploadFileName: 'imgUpload',
                downloadFieldName: val
            });

        }

}

The Library works, with an own modification like this:

window.inlineAttach.Editor = function(instance) {

    var input = instance;

    return {
        getValue: function() {
            return input.value;
        },
        setValue: function(val) {
            input.value = val;
        },
        targetElement: function() {

            return instance;

        }
    };
};

With my solution, the internal reference to the object is given by itself. I can get the instance @the method: uploadFile using editor.targetElement() ...

The current version depends on the Lookposition... If I click to "First" the position 1 will be overgiven to the function "attachInlineUploadByLookPos" and the next click too... :P In my perception, i have no way to get the "only" correct container which is been affected by using the dropfunction.. or?

I'd like to have a clear and simple solution.. Could I get a advice from you, please?

Is there a way to get the e.originalEvent? :P

one

Undo support

Pressing undo (CTRL+Z) after uploading a file, currently restores the uploading file... placeholder - adding the placeholder to the document history should probably be avoided.

I'm using CodeMirror 5.25.2.

Inputfield

Implement the native input field functionality inlineAttach.attachToInput

Support Text Files

As suggested by @choonkeat, allow dropping text files which instead of uploading will insert the contents in the text area.

Dynamic extraParams

Hello, I have a question to ask about it.
ExtraParams contains the token, how to update the parameters in the extraParams when the token expires?

How to use with Backbone?

I'm currently building my first website with Backbone and I would like to use InlineAttachement. I'm kinda lost in how I should use this though.

Does anybody have an example of how to use this in a Backbone view? All tips are welcome!

Angular documentation

There does not seem to be adequate angular documentation. What is the dependency that should be injected into the app?

WebDAV support

Thanks for this package, still perfectly usable 5 years after the last commit! It would be nice if uploading to WebDAV could be supported.

I have successfully implemented it, but the requests/response from and to WebDAV are quite different than the package currently supports. A proper pull request would need quite a bit of refactoring, and I am also not so sure how to stay backwards comptible.

Since I /only/ need WebDAV support, I have overridden the uploadFile method, maybe someone will find it useful or it can be included in the package core one day.

WebDAV uses a dynamic uploadUrl (uploading a file foo.jpg to https://example.com needs a PUT request to https://example.com/foo.jpg, while the file contents should not be encapsulated in any FormData, rendering uploadFieldName obsolete). The response does not contain any data, only the HTTP status code tells if the upload was successful. The resulting filename is the same as the request url, and cannot be extracted from the response.

This is my adaption of uploadFile, to support WebDAV (and only WebDAV), override it like this:

inlineAttachment.prototype.uploadFile = function(file) {

    var me = this,
      xhr = new XMLHttpRequest(),
      settings = this.settings,
      extension = settings.defaultExtension || settings.defualtExtension;

    // Attach the file. If coming from clipboard, add a default filename (only works in Chrome for now)
    // http://stackoverflow.com/questions/6664967/how-to-give-a-blob-uploaded-as-formdata-a-file-name
    if (file.name) {
      var fileNameMatches = file.name.match(/\.(.+)$/);
      if (fileNameMatches) {
        extension = fileNameMatches[1];
      }
    }

    var remoteFilename = "image-" + Date.now() + "." + extension;
    if (typeof settings.remoteFilename === 'function') {
      remoteFilename = settings.remoteFilename(file);
    }

    xhr.open('PUT', settings.uploadUrl + '/' + remoteFilename);

    xhr.onload = () => {
        var filename, newValue;
        if (xhr.status === 200 || xhr.status === 201 || xhr.status === 204) {
            filename = xhr.responseURL;
            newValue = this.settings.urlText.replace(this.filenameTag, filename);
        } else {
            newValue = "";
        }
        var text = this.editor.getValue().replace(this.lastValue, newValue);
        this.editor.setValue(text);
        return false;
    };
    xhr.send(file);
    return xhr;
};

// use it like regular
inlineAttachment.editors.codemirror4.attach(this.codeMirror, {
    progressText: '[[Uploading file...]]',
    urlText: '[[{filename}]]',
    uploadUrl: 'http://examplecom:8000/uploads',
});

Issues when adding extra headers

In issue #46 support for extraHeaders was added; I attempted to use this now by adding the following to my InlineAttachment configuration:

{
  extraHeaders: { "Accept": "application/json" }
}

Whenever InlineAttachment attempts to upload files now, I get this error:

Uncaught InvalidStateError: Failed to execute 'setRequestHeader' on 'XMLHttpRequest': the object's state must be OPENED.

I tried moving the block that sets the headers down until after the XMLHttpRequest has been opened, but this did strangely enough not seem to have any effect; the error still occured. I'm not familiar with this code, or really XMLHttpRequest in general, so I'm not quite sure what is going on here. I'd be happy to fix and submit a pull request, but some ideas about what might be going on here would be great.

Why don't you submit this package to npm

Hi,
Thank you for the great library that makes every JS application easier to handle the file uploads.

Anyway, recently there few people using bower to solve their dependencies but use npm (or yarn) directly. So could you submit this library to npm?
That makes us able to describe the dependence on this library directly on package.json.

Copy-paste weirdness

Drag drop works, but copy paste yields a different file.

Dragging
logo11w

Copy pasting
image

i'll get the same file regardless of what i'm pasting. hmm its happening on github textarea too

Chrome: 39.0.2171.95 (64-bit)

Support using a function instead of a plain string for urlText

I'd like to expand the syntax used for markdown in the urlText, like by specifying the height & width (an extension to normal markdown):

![file_name)(/imgs/123456789.png =120x60)

Though I don't want to hard-code a default size, and instead customize it based on data returned from the server. My thought is that a function could be set for urlText that will be passed in the data returned from the server. The function is expected to return a string that will be placed literally into the textarea (so if you opt to use the function, you must make sure to include the attachment's name in the string).

urlText not working

I have this in my js file:

$(document).ready(function() {
  $(function() {
    $('textarea').inlineattachment({
      uploadUrl: 'upload_attachment.php',
      urlText: "testing" //this is not working, expecting "testing" to replace the default "![Uploading file...]()" text in textarea
    });
  });
});

Am I using this wrongly or is there a bug somewhere?

downloadFieldName

When I upload a file the server I'm dealing with returns a json in the format, how can I tell it where the URL from this response is? It looks downloadFileName looks to be the one but how exactly?

files: [{name:8001020224.png, size:34093, type:image/jpeg,…}]
0: {name:8001020224.png, size:34093, type:image/jpeg,…}
deleteType: "DELETE"
deleteUrl: "?file=8001020224.png"
name: "8001020224.png"
size: 34093
type: "image/jpeg"
url: "http://localhost/1387896081/8001020224.png"

I hope to get the origin filename

I found that the filename will be replaced by image-timestamp.ext, but I want to get the real name of the file uploaded. How to solve it?

Differentiate txt file and images

If you drag and drop a txt file, CodeMirror will read it automatically .

So I wish v2 will differentiate txt file and images ,

if it's a txt file ,just read it . when it's a image ,then upload it.

Browser Compatibility Check

Check the current browsers for available functionality and add this to the README.md

Support

Browser Drag & Drop Paste
Internet Explorer 8 ? No
Internet Explorer 9 ? No
Internet Explorer 10 ? No
Internet Explorer 11 Yes No
Firefox Yes No #25
Chrome Yes Yes
Safari ? ?
Opera ? ?

Checklist

Ubuntu

  • Firefox
  • Chromium
  • Chrome
  • Safari?
  • Opera?

Windows 8

  • Internet Explorer 8
  • Internet Explorer 9
  • Internet Explorer 10
  • Internet Explorer 11
  • Firefox
  • Chrome
  • Safari
  • Opera

OS X

  • Firefox
  • Safari
  • Opera

Firefox

Compatible with at least the drag-drop event, ignore paste so it doesn't generate errors.

Drop to the coursor.

Hi. We use InlineAttacjment with CodeMirror 5.6.0.

When dropping file to the editor it drop to the previous coursor position (not to the line where we release mouse).

Do you know about this?

Is this a correct behavior?

Support TinyMCE

First I want to say this is an awesome plugin, I hadn't test it yet, but from demo I can see this is THE functionality I was looking for.
Thank You for sharing this awesome piece of code.
I noticed that You have CodeMirror integration, do You plan to add tinyMCE support? right now when placing images into TinyMCE they are included as base64, instead I would like to include them like You plugin is doing.

Maybe You already used Your plugin with TinyMCE?

Webpack support

What's currently the recommended path for integration with applications built with webpack, and is there any interest in upgrading this package to support ES6 / webpack / "whatever I should be calling this modern JS development stack"?

I've started some work over at https://github.com/bowtie-io/InlineAttachment that I'll probably use for our applications and I'd like to figure out what your thoughts on this are.

Can you provide demo for the simplemde?

Can you provide jsfiddle?

I don't know how Vue + SimpleMDE + InlineAttachment does it

No backend code is required, I just want to know how the front end is going to do it.

Question: Why does this library work only on Chrome?

Hello Roy, do you know the specific reasons why the library works only in Chrome? We love this functionality and if you can guide us, we can contribute to extend it for other browsers - specially FF and Safari.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.