How to do file upload in e2e AngularJS tests? How to do file upload in e2e AngularJS tests? angularjs angularjs

How to do file upload in e2e AngularJS tests?


You can upload files using Javascript blobs. This requires the FileApi, which isn't compatible with older browsers (http://caniuse.com/fileapi). But since you mentioned using drag and drop uploads, which uses the FileApi, it shouldn't matter too much.

There are two ways you can upload files using the blob API. One is very easy and the other is simply a continuation of the first.

Using Javascript, you can create a new blob with:

var blob = new Blob("content", contentType);

For example, this will create a blob object that contains the text "Hello World!".

var foo = new Blob("Hello World!", {type: "text/plain"});

You could also use the following method is better for non-plaintext files, such as pdf's. You have to convert the file to Base64 (you can use something like this) and create the blob using the Base64 data.

Use this function (a slightly modified version of this) to create the blob.

function b64toBlob(b64Data, contentType, sliceSize) {b64Data = b64Data.replace(/\s/g, '');contentType = contentType || '';sliceSize = sliceSize || 1024;function charCodeFromCharacter(c) {    return c.charCodeAt(0);}var byteCharacters = atob(b64Data);var byteArrays = [];for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {    var slice = byteCharacters.slice(offset, offset + sliceSize);    var byteNumbers = Array.prototype.map.call(slice, charCodeFromCharacter);    var byteArray = new Uint8Array(byteNumbers);    byteArrays.push(byteArray);}var blob = new Blob(byteArrays, {type: contentType});return blob;}

For example, this will create a PDF blob object.

var pdf = "JVBERi0xLjQKJcfsj6IKNSAwIG9...=="; //base64 encoded file as a Stringvar pdfBlob = b64toBlob(pdf, "application/pdf", 1024);

After you create the blob with one of the methods above, it can be treated as a file. For example, you could put the file into a FormData object (if you're doing uploads like this):

var fd = new FormData();fd.append("uploadedFile", pdfBlob, "My PDF.pdf"*);

*Filename parameter only seems to work on Chrome as of now.