Upload file from javascript

1
Hi I want to upload my product image from javascript. I have this: var name="1234"; var description="1234"; var price="1234"; var stock="1234"; mx.data.create( { entity: "ECommerceTemplate.Product", callback: function(n) { n.set("Name_", name); n.set("Description_", description); n.set("Price_", price); n.set("Stock_", stock); mx.data.commit( { mxobj: n, callback: function() { console.log("Object committed") }, error: function(t) { console.log("Error occurred attempting to commit: " + t) } } ) }, error: function(t) { console.log("an error occured: " + t) } } ) How can I upload a file document/image/whatever from the javascript? Thankyou very much.
asked
1 answers
3

You can always check how Mendix is doing this; you find in your install dir for example: C:\Program FilesMendix\5.18.0runtime\mxclientsystem\mendix\lib\Upload.js

You can re-use this upload module, in the way "mxui/widget/FileInput" is doing. However current Mendix versions compile and valide the code and will not allow you to use it in the same way.

As work around, Just copy the file into your widget...

Here some details how you can upload: Use the new HTML 5 data upload

_uploadViaFormData: function() {
            var _8 = this._determineUrl(),
                _9 = new FormData(),
                _a = this.form.mxdocument.files[0],
                _b = this;
            _9.append("mxdocument", _a);
            var _c = new XMLHttpRequest();
            _c.onreadystatechange = function() {
                if (_c.readyState == 4) {
                    _b.finishUpload(true);
                    if (_c.status == 200) {
                        _b.callback && _b.callback();
                        return;
                    }
                    var _d = _b._getError(_c.responseText);
                    _b.error && _b.error(_d || undefined);
                }
            };
            this.startUpload(true);
            _c.open("post", _8, true);
            _c.send(_9);
        },

Or the legacy upload for HTML4

   _uploadViaIFrame: function() {
            var _11 = this.form,
                _12 = this;
            _11.action = this._determineUrl();
            this.startUpload(false);
            _1.send({
                form: _11,
                handleAs: "json",
                handle: function(_13) {
                    try {
                        if (_13 instanceof _2) {
                            _12.error && _12.error(_13);
                        } else {
                            _12.callback && _12.callback();
                        }
                    } finally {
                        _12.finishUpload(false);
                    }
                }
            });
        }
answered