0

I'm trying to get ajax file uploads to work but I'm struggling with an example I found here but trying to Google the error produces nothing relevant.

Original example: jQuery Ajax File Upload

var formData = new FormData($('#frmBreakdownItem')[0]);
formData.append('Document', file);

This results in the following error in the Chrome console;

Uncaught TypeError: formData.append is not a function
    at jQuery.fn.init.callback (14:1336)
    at processCallback (bootbox.js:86)
    at HTMLButtonElement.<anonymous> (bootbox.js:568)
    at HTMLDivElement.dispatch (jquery-3.1.1.js:5201)
    at HTMLDivElement.elemData.handle (jquery-3.1.1.js:5009)

I did also try moving on to using FileReader() and while I do get a byte array, I believe some process is corrupting/removing data which is resulting in the uploaded file becoming unreadable.

My code using FileReader()

var file = document.getElementById('Document').files[0];

var reader = new FileReader();
reader.readAsText(file);
reader.onload = function (event) {

var result = event.target.result;

var fileName = file.name;
var fileMimetype = file.type;

$.post(
    url,
    {
        id: breakdownItemId,        
        data: result,
        mime: fileMimetype,
        name: fileName
    },
    function (response) {

        console.log(response);

    }
);

...and in my controller (C# MVC ASP.NET) I store the converted byte array as such:

byte[] fileBytes = Encoding.UTF8.GetBytes(data);

I store this file in Azure Blob Storage which detects the file as content type application/octet-stream. Uploading the same file to the same blob storage container with the MS Storage explorer stores a file with a different size, and the correct content type.

I'm now at a complete loss as to what to do next.

Stuart Frankish
  • 818
  • 1
  • 11
  • 27
  • what does `console.log(formData)` show? – Scaramouche Apr 04 '18 at 14:59
  • I get an object with the values from another form on the page. I'll elaborate here a little - there is a main form on the page and a popup (using bootbox.js) displaying another [child] form. even though the code above is targeting the correct form - I am getting values from the main form instead. – Stuart Frankish Apr 04 '18 at 15:31
  • from where I stand, that error could be related to two aspects. one: `formData` is not jquery object or two: `file` is not a valid arg, maybe inspect those and check with the [docs](https://api.jquery.com/append/) – Scaramouche Apr 04 '18 at 16:03

1 Answers1

0

I found out what the issue was in the end.. Another library we were using was overriding the default FormData with a function called FormData() { ... }

Renaming that function has resolved the issue.

Stuart Frankish
  • 818
  • 1
  • 11
  • 27