3

In Sharepoint 2013, is it possible to drag and drop a file (.jpg , .pdf, .png) to a custom list as an attachment? If so, can this be achieved by using a script (JS, jquery)? So, if a user is reporting a bug (NewForm.aspx), and he has a screenshot of the error message saved as a .jpg, I would want him to be able to drop this file into a drop zone on the form.

Can this scenario work - I would be very grateful for your suggestions?

2 Answers 2

1

Try the code below:

<style type="text/css">
        .droppable {
            background: #08c;
            color: #fff;
            padding: 100px 0;
            text-align: center;
        }

            .droppable.dragover {
                background: #00CC71;
            }
    </style>

    <script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script type="text/javascript">
        function makeDroppable(element, callback) {

            var input = document.createElement('input');
            input.setAttribute('type', 'file');
            input.setAttribute('id', 'dragdropContent');
            input.setAttribute('multiple', true);
            input.style.display = 'none';

            input.addEventListener('change', triggerCallback);
            element.appendChild(input);

            element.addEventListener('dragover', function (e) {
                e.preventDefault();
                e.stopPropagation();
                element.classList.add('dragover');
            });

            element.addEventListener('dragleave', function (e) {
                e.preventDefault();
                e.stopPropagation();
                element.classList.remove('dragover');
            });

            element.addEventListener('drop', function (e) {
                e.preventDefault();
                e.stopPropagation();
                element.classList.remove('dragover');
                triggerCallback(e);
            });

            element.addEventListener('click', function () {
                input.value = null;
                input.click();
            });

            function triggerCallback(e) {
                var files;
                if (e.dataTransfer) {
                    files = e.dataTransfer.files;
                } else if (e.target) {
                    files = e.target.files;
                }
                callback.call(null, files);
            }
        }
        $(function () {

            String.prototype.format = function () {
                var args = [].slice.call(arguments);
                return this.replace(/(\{\d+\})/g, function (a) {
                    return args[+(a.substr(1, a.length - 2)) || 0];
                });
            };

            var element = document.querySelector('.droppable');
            function callback(files) {
                // Here, we simply log the Array of files to the console.
                //console.log(files);
                var fileName = files[0].name;
                // Construct the endpoint. mydoc is document library name                

                var reader = new FileReader();
                reader.file = files[0];
                reader.onload = function (event) {
                    var arrayBuffer = event.target.result;

                    //var fileData = '';
                    //var byteArray = new Uint8Array(arrayBuffer);
                    //for (var i = 0; i < byteArray.byteLength; i++) {
                    //    fileData += String.fromCharCode(byteArray[i]);
                    //}

                    var fileEndpoint = String.format(
                        "{0}/_api/web/lists/getByTitle('{1}')/RootFolder/files" +
                        "/add(overwrite=true, url='{2}')",
                        _spPageContextInfo.webAbsoluteUrl, 'mydoc', fileName);

                     //Add the file to the SharePoint folder.
                    $.ajax({
                        url: fileEndpoint,
                        type: "POST",
                        data: arrayBuffer,//fileData,
                        processData: false,
                        headers: {
                            "X-RequestDigest": jQuery("#__REQUESTDIGEST").val(),
                            "accept": "application/json;odata=verbose",
                            "content-length": arrayBuffer.byteLength,
                            //"IF-MATCH": itemMetadata.etag,
                            //"X-HTTP-Method": "MERGE"
                        },
                        success: function (data, b, c) {
                            alert('File upload succeeded.');
                        },
                        error: function (a, b, err) {
                            alert('Error: ' + err.responseText);
                        }
                    })
                };
                reader.onerror = function (e) {
                    alert(e.target.error);
                }
                var arrayBuffer = reader.readAsArrayBuffer(files[0]);                
            }
            makeDroppable(element, callback);                 
        })

    </script>

    <div class="droppable">
        <p>Drag files here or click to upload</p>
    </div>
2
  • Thanks a lot for your code - unfortunately, I can't drop/upload objects in the zone, as I get "Error: undefined". This happens in custom list as well as task list forms... Do you have and idea what causes this behavior? Jan 22, 2018 at 11:36
  • Can you also tell me, why certain controls in your code are disabled? Jan 22, 2018 at 17:20
0

Haven't done exactly this myself on a NewForm.aspx, but looking at how it works OOB, I would say it is possible by modifying the NewForm.aspx. You'd first need to investigate how the OOB attachment functionality works, and just do the same when user drops attachment on top of the form, or some specific area that reads "drag&drop files here".

I've used FileDrop on my Publishing Page Layout, and code something like this:

var attZone = new FileDrop('fdzone');

// FileList is a simple array-like object
// with many useful File-related methods:
var activeUpload = new fd.FileList;
attZone.multiple(true);

attZone.event('send', function (files) {
    files.each(function (file) {

        file.event('done', function (xhr) {
            var resp = JSON.parse(xhr.response).d;

            CheckinArticleAttachment(resp).done(UpdateArticleAttachmentList());

However, NewForm.aspx might contain file upload functionality of its own, so it might just be sufficient to update the local file path to some hidden field and the form takes care of the rest when you press OK to save the list item.

2
  • Thank you very much for your answer, Jussi! Could you give me an additional hint on how to integrate FileDrop into my form template, as I'm fairly new to this game? Jan 20, 2018 at 12:58
  • First create new "New" form for the list using SharePoint Designer, and add reference to FileDrop + the required code. Look at the FileDrop samples.
    – Jussi Palo
    Jan 22, 2018 at 8:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.