0

I've got a microservice (in NancyFx) that works as expected for the following cURL command:

curl --verbose   --form file=@"C:\test\image.png"  http://localhost:8080/file/upload

The file shows up inside Nancy as expected at:

context.Request.Files[0]  //The file bytes are here, yeah!!

Now I've got to get my web-client to send a selected file to the same service, in the same way.

TLDR; You can skip my failure examples below if you'd like

I've tried several versions of the following with no success:

    var uploadForm = new FormData();  
    // Add the file to the request.
    uploadForm.append("file", file, name);
    var xhr = new XMLHttpRequest();
    xhr.open('POST', 'http://localhost:8080/file/upload', true);
    xhr.onload = function() {
        if (xhr.status === 200)
            alert('File ' + name + 'Upload successfully!!!');
        else errorFn("Upload Failure on file " + name);
    };

    //Send the data
    xhr.send(uploadForm);

and several versions of the following, also with no success:

    var postConfig = {
        url: 'http://localhost:8080/file/upload',
        data: uploadForm,
        processData: false, //tries without this as well
        type: "POST",
        dataType: "application/x-www-form-urlencoded; charset=UTF-8",
        cache: false,
        success: successFn,
        error: errorFn
    }
    $.ajax(postConfig);

I've tried the above with

  1. file = direct reference to $('MyFileSelectorControl').files[0]
  2. file being set with the following code:

    var reader = new FileReader();
    reader.onload = function (result) {
        var fileContent = new Uint8Array(result.target.result);
        var encContent = new SP.Base64EncodedByteArray();
        for (var b = 0; b < fileContent.length; b++) {
            encContent.append(fileContent[b]);
        }
        <Set file = encContent and send AJAZ as above>
    };
    reader.readAsArrayBuffer(fileInput);
    
    1. Setting file = to fileContent above (IOW, after it has been through the reader, but not encoded.)

How do I submit this file from javascript (jQuery or standard) so that it works like it does from cURL?

SvdSinner
  • 951
  • 1
  • 11
  • 23

1 Answers1

0

Here is the code that finally worked. (Admittedly, I had thought I had already tried this and said so in my question)

var file = $('MyFileSelectorControl').files[0];
var uploadForm = new FormData();  
// Add the file to the request.
uploadForm.append("file", file, name);
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://localhost:8080/file/upload', true);
xhr.onload = function() {
    if (xhr.status === 200)
        alert('File ' + name + 'Upload successfully!!!');
    else errorFn("Upload Failure on file " + name);
};

//Send the data
xhr.send(uploadForm);
SvdSinner
  • 951
  • 1
  • 11
  • 23