如何将给定的curl命令复制为jquery ajax请求

How can I duplicate the given curl command as a jquery ajax request?

本文关键字:复制 jquery ajax 请求 命令 curl      更新时间:2023-09-26

我有以下REST API调用示例-

curl -u "{username}":"{password}" -X POST '
-F "images_file=@test.jpg" '
"https://gateway.watsonplatform.net/visual-recognition-beta/api/v2/classify?version=2015-12-02"

我想将上述调用作为一个标准的ajax请求来执行。这就是我目前所拥有的

cropper.getCroppedCanvas().toBlob(function(blob){
        var uploadData = new FormData();
        uploadData.append('images_file',blob);
        $.ajax('https://gateway.watsonplatform.net/visual-recognition-beta/api/v2/classify?version=2015-12-02', {
        method: "POST",
        data: uploadData,
        processData: false,
        contentType: false,
        beforeSend: function (xhr) {
            xhr.setRequestHeader('Authorization', 'Basic ODdlOTTZIeg==');
        },
        success: function (data) {
            console.log('Upload success');
            console.log(data);
        },
        error: function (data) {
            console.log('Upload error');
            console.log(data);
        }
    })
    })

我得到一个错误作为-

"{"code":400,"error":"Could not classify. Verify that valid images were uploaded."}"

我的预感是,在上面的ajax调用中,cURL的-F image_results=@test.jpg没有得到正确的模拟。

getCroppedCanvas()是来自cropperjs库的函数调用。

formDatablob一起使用,如下所示:

formdata.append("myfile", myBlob, "filename.txt");

参见文件

使用append()方法时,可以使用第三个可选参数在发送到服务器的Content-Disposition标头中传递文件名。如果未指定文件名(或不支持该参数),则使用名称"blob"。

因此,对于您的案例:

cropper.getCroppedCanvas().toBlob(function(blob){
    var uploadData = new FormData();
    var filename = "your-file-name-with-suffix";
    uploadData.append('images_file',blob,filename);
    //$.ajax(...);
});