0

I have a C# Rest API method which accepts System.IO Stream object as argument and I am trying to pass a file to this C# method as a file stream using Ajax call. Please suggest how to do this? I tried two ways-

  1. Creating FormData object in JavaScript and
  2. Creating File object in JavaScript.

C# method

[WebInvoke(UriTemplate = "/{businessObjectId}/uploadAttachment?filename={filename}&caption={caption}")]
public Message UploadAttachment(string filename, string caption, Stream stream, string businessObjectId){....}

Ajax Method

$("input[name*='btnUpload']").live("click", function () {
    addGlobalAttachment();
});
function addGlobalAttachment() {
    var fileData = $("input[id*='fileUpload']");
    var fileName = fileData[0].files[0].name;
    var fileCaption = $("input[name*='txtFileCaption']").val();
    var friendlyID = $(".order").html();
    var fileInput = new File(fileData[0].files, fileName, { type: "text/plain", lastModified: Date(0) });
    var URL = "http://localhost:62059/Order/" + friendlyID + "/uploadAttachment?filename=" + fileName + "&caption=" + fileCaption;
    $.ajax({
        type: 'POST',
        url: URL,
        data: fileInput,
        processData: false,
        contentType: 'application/octet-stream',
        success: function (attachmentResult) {
                debugger;
            }
        },
        error: function (result) {
            
        }
    });
}
Omi
  • 427
  • 7
  • 21
  • 42
  • 1
    You should be using IFormFile and not the stream. – Chetan Nov 08 '22 at 04:36
  • @Chetan Could you please share some example? – Omi Nov 08 '22 at 04:47
  • sure. https://stackoverflow.com/questions/46903310/uploading-file-using-ajax-in-asp-net-core . – Chetan Nov 08 '22 at 04:51
  • https://stackoverflow.com/questions/64479129/upload-file-on-server-webfolder-and-post-json-data-at-the-same-using-asp-net-web/64480196#64480196 – Chetan Nov 08 '22 at 04:54
  • @Chetan Thanks for sharing the examples, but I have a challenge that I can not change the signature of my API method. I have Stream object in the argument and when I pass data using FormData object, I am not getting any data in the stream object of my C# method. – Omi Nov 08 '22 at 07:26

0 Answers0