1

Here is my current setup to upload a file to my webapp:

HTML:

<iframe name="myframe" id="frame1" class="hidden"></iframe>
<form target="myframe" method="post" enctype="multipart/form-data" action="/api/User/collection">
    <input type="file" name="file" />
    <input type="submit" value="Upload" />
</form>

Controller:

// POST api/user/collection
[HttpPost("collection")]
public ActionResult<IResponse> SetCollection(IFormFile file)
{
    var collection = fileDeflator.UnzipAndGetCollection(file);

    if (collection == null)
        return BadRequest(new BaseResponse("The collection file is invalid."));

    return base.SetUserCollection(collection);
}

It's working, except that there is no feedback at all for the client.

I would prefer that the JSON returned by the server be caught in a javascript callback on the web page (not the iframe) and be parsed to refresh a section on the page.

Is that possible with the nature of form submit ?

Kirk Larkin
  • 84,915
  • 16
  • 214
  • 203
Bruno
  • 4,685
  • 7
  • 54
  • 105
  • https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onsubmit –  Jan 02 '19 at 15:53
  • @Amy I don't think I will have access to the JSON that the server returned with that method? – Bruno Jan 02 '19 at 15:59
  • You use that method to cancel the form submit and submit it yourself using AJAX, thus giving you access to the response in JS. –  Jan 02 '19 at 16:00
  • Possible duplicate of https://stackoverflow.com/questions/35752937/get-json-response-from-form-submit/35753109 –  Jan 02 '19 at 16:04
  • @Amy Thanks for all the info, I am looking into a solution using your hints, but I don't want to use JQuery... – Bruno Jan 02 '19 at 16:11
  • Anything written in jQuery is easily converted to plain JS. –  Jan 02 '19 at 16:12
  • @Amy this is what I am trying to do right now – Bruno Jan 02 '19 at 16:14

1 Answers1

1

I ended with something working as I wanted with the helpful resources that Amy provided.

Here is the solution:

<form id="formSendCollection">
    <input type="file" id="fileCollection" name="fileCollection" />
    <span onclick="submitCollection();" class="button is-primary">Submit</span>
</form>

function submitCollection() {
    var fdata = new FormData();
    var fileCollection = document.getElementById('fileCollection').files[0];
    fdata.append("fileCollection", fileCollection);

    sendAjax('/api/User/Collection', fdata, function (body) {
        vueApp.modelUser.collection = JSON.parse(body);
    });
}

function sendAjax(url, body, callback) {
    var xmlhttp = new XMLHttpRequest();

    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState === XMLHttpRequest.DONE) {
            callback(xmlhttp.responseText);
        }
    };

    xmlhttp.open('POST', url, true);
    xmlhttp.send(body);
}
Bruno
  • 4,685
  • 7
  • 54
  • 105