Posting File Input as FileReader Binary Data through AJAX Post

前端 未结 2 883
执笔经年
执笔经年 2020-12-04 16:38

I am trying to post an attachment uploaded to an HTML file input to a web page through a rest API. The API documentation states that the post is a straight binary content as

2条回答
  •  盖世英雄少女心
    2020-12-04 17:18

    var file;

            $('#_testFile').on("change", function (e) {
                file = e.target.files[0];
            });
            $('#_testButton').click(function () {
                var serverUrl = '/attachmentURL';
    
                $.ajax({
                    type: "POST",
                    beforeSend: function (request) {
                        request.setRequestHeader("Content-Type", file.type);
                    },
                    url: serverUrl,
                    data: file,
                    processData: false,
                    contentType: false,
                    success: function (data) {
                        console.log("File available at: ", data);
                    },
                    error: function (data) {
                        var obj = jQuery.parseJSON(data);
                        alert(obj.error);
                    }
                });
            });
    

提交回复
热议问题