将表单发布到api端点并在javascript回调中获取响应

时间:2019-01-02 15:52:08

标签: c# asp.net-core asp.net-core-webapi

这是我当前的设置,用于将文件上传到我的网络应用程序:

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>

控制器:

// 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);
}

工作正常,除了客户端完全没有反馈。

我希望服务器返回的JSON被捕获在网页(而非iframe)上的javascript回调中,并被解析以刷新页面上的某个部分。

form的性质是否可以提交?

1 个答案:

答案 0 :(得分:1)

最后,我想通过艾米提供的有用资源来完成一些工作。

这是解决方案:

<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);
}