如何在e2e AngularJS测试中进行文件上传? [英] How to do file upload in e2e AngularJS tests?

查看:136
本文介绍了如何在e2e AngularJS测试中进行文件上传?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的一个观点中,我有一个文件上传控件。它支持文件上传,通过拖放,或通过按钮单击后打开的标准文件对话框。

In one of my views, I have a file upload control. It supports file uploading either via drag and drop, or via the standard file dialog opened after a button click.

如何在我的e2e测试中执行此操作 1

How to do this in my e2e tests1?

1 这两个选项之一就足够了>

1 Just one of the two options will be enough

推荐答案

您可以使用Javascript blob上传文件。这需要与旧浏览器不兼容的FileApi( http://caniuse.com/fileapi ) 。但是,由于您提到使用拖放上传功能(使用FileApi),因此不要太多。

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.

有两种方法可以使用blob API上传文件。一个很简单,另一个只是第一个的延续。

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.

使用Javascript可以创建一个新的blob:

Using Javascript, you can create a new blob with:

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

例如,这将创建一个包含文本Hello World!的blob对象。 p>

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

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






您还可以使用以下方法更好非纯文本文件,如pdf。您必须将文件转换为Base64(您可以使用)和使用Base64数据创建Blob。


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.

使用此功能(稍微修改版本的这个)来创建blob。

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;
}

例如,这将创建一个PDF blob对象。

For example, this will create a PDF blob object.

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






使用其中一种方法创建blob以上,它可以被视为一个文件。例如,您可以将该文件放入FormData对象(如果您正在进行上传,例如 ):

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

* Filename参数现在似乎只适用于Chrome。

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

这篇关于如何在e2e AngularJS测试中进行文件上传?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆