Posting a File and Associated Data to a RESTful WebService preferably as JSON

后端 未结 11 1032
没有蜡笔的小新
没有蜡笔的小新 2020-11-22 10:45

This is probably going to be a stupid question but I\'m having one of those nights. In an application I am developing RESTful API and we want the client to send data as JSON

11条回答
  •  梦谈多话
    2020-11-22 11:40

    FormData Objects: Upload Files Using Ajax

    XMLHttpRequest Level 2 adds support for the new FormData interface. FormData objects provide a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using the XMLHttpRequest send() method.

    function AjaxFileUpload() {
        var file = document.getElementById("files");
        //var file = fileInput;
        var fd = new FormData();
        fd.append("imageFileData", file);
        var xhr = new XMLHttpRequest();
        xhr.open("POST", '/ws/fileUpload.do');
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4) {
                 alert('success');
            }
            else if (uploadResult == 'success')
                 alert('error');
        };
        xhr.send(fd);
    }
    

    https://developer.mozilla.org/en-US/docs/Web/API/FormData

提交回复
热议问题