3

I am testing some API functions through localhost using an HTML website with ajax to make this api calls, everything works great till i bumped to this api call:

localhost/uploadFile?file=?????&userID=123421

I have searched everywhere about a way to upload a file and send it with API but could not find anything helpful, what I know about this API call(uploadFile) is that it can only be a POST request.

So this is what I do:

HTML Code:

<form method="post" id="form">
<input type="file" name="file" id="file">
<button type="submit" onclick="check(this.form)" id="submitbtn" >Send</button>
</form>

Ajax Script:

function check(form){

     $.ajax({
        url: "http://localhost/uploadFile&file="+document.getElementById("file").value+"&userID=123421",
        type: "POST",
        dataType: "json",
        success: function (result) {
            switch (result) {
                case true:
                    alert(result);
                    break;
                default:
                    alert(result);
            }
        },
        error: function (xhr, ajaxOptions, thrownError) {
        alert(xhr.status);
        alert(thrownError);
        }
    });
}

I found this tutorial to use ajax to upload a file but it only saves it to the server how can I send it with the api? The mystery is in the parameter file what can I save there?? I printed the value of document.getElementById("file").value and it's just somthing like C:/fakepath/fileName.txt, If you have any idea how this works would be very helpful I am new to ajax and I am open to other web programming languages, except php for some api reasons...

Programmer Man
  • 1,314
  • 1
  • 9
  • 29
  • Are you rolling your own API? You mention API several times, but don't appear to mention _which_ API you are using.... – random_user_name Aug 19 '17 at 13:09
  • Also - please clarify - are you looking to upload the file _contents_ via the AJAX call? As you have it written presently, you are only uploading the file name. If you want the contents, you'll need to read the contents into a string and send the entire contents. – random_user_name Aug 19 '17 at 13:10
  • I am working with NXT API but the request are very complex so i decided to explain it as easy as possible. – Programmer Man Aug 19 '17 at 13:12
  • http://igstan.ro/posts/2009-01-11-ajax-file-upload-with-pure-javascript.html – random_user_name Aug 19 '17 at 13:12
  • @cale_b If you see the api call uploadTaggedDatat here http://107.170.3.62/test?requestTag=DATA it takes file as a parameter that's what I want to do – Programmer Man Aug 19 '17 at 13:18
  • Understood. But, JS is probably the hardest language to make this happen with, if at all. PHP for example can fairly trivially read a file and send it via AJAX. There are _ways_ to upload a file to a server, utilizing javascript, but they are not trivial. – random_user_name Aug 19 '17 at 13:27

0 Answers0