如何通过JavaScript以编程方式将文件添加到html输入(类型文件)?
我正在写这段代码,它要求我通过Q-unit进行单元测试。我有一个输入字段,用户在其中上传一个文件,然后我使用Javascript的“FileReader”读取它,对其进行一些处理。但是,在编写单元测试时,我无法将文件上载到输入字段,以便对我的函数进行单元测试。我目前正在做的工作如下:如何通过JavaScript以编程方式将文件添加到html输入(类型文件)?,javascript,unit-testing,qunit,Javascript,Unit Testing,Qunit,我正在写这段代码,它要求我通过Q-unit进行单元测试。我有一个输入字段,用户在其中上传一个文件,然后我使用Javascript的“FileReader”读取它,对其进行一些处理。但是,在编写单元测试时,我无法将文件上载到输入字段,以便对我的函数进行单元测试。我目前正在做的工作如下: //Unit test bit var done = assert.async(); var pngFile = new File([""],"../../img/test.jpg"); inputElement.
//Unit test bit
var done = assert.async();
var pngFile = new File([""],"../../img/test.jpg");
inputElement.files[0] = pngFile;
photoMosaic.extractImageFromInput(inputElement);
setTimeout(function() {
assert.equal(photoMosaic.getImageName(),"../../img/test.jpg", "Correct file format test succeeds" );
done();
}, 500 );
//after some checkings and stuff
var reader = new FileReader();
// Closure to capture the file information.
reader.onload = (function(theFile) {
return function(e) {
// Render image
this.MainImage = document.createElement('IMG');
this.MainImage.src = e.target.result;
this.MainImage.setAttribute("name",theFile.name);
return this.MainImage;
};
})(file);
reader.readAsDataURL(file);
extractImageFromInput中提取图像的代码如下所示:
//Unit test bit
var done = assert.async();
var pngFile = new File([""],"../../img/test.jpg");
inputElement.files[0] = pngFile;
photoMosaic.extractImageFromInput(inputElement);
setTimeout(function() {
assert.equal(photoMosaic.getImageName(),"../../img/test.jpg", "Correct file format test succeeds" );
done();
}, 500 );
//after some checkings and stuff
var reader = new FileReader();
// Closure to capture the file information.
reader.onload = (function(theFile) {
return function(e) {
// Render image
this.MainImage = document.createElement('IMG');
this.MainImage.src = e.target.result;
this.MainImage.setAttribute("name",theFile.name);
return this.MainImage;
};
})(file);
reader.readAsDataURL(file);
但是,它给了我以下错误:
GET data: net::ERR_INVALID_URL
我曾尝试将图像放在与测试相同的目录中,并仅使用“test.jpg”作为路径,但没有成功。任何帮助都将不胜感激。您是否尝试过绝对URL(
http://www.yoursite.com/path/file.ext
)?@ScottMarcus我试过了,是的,运气不好。另一件需要注意的事情是,我使用的是readAsDataURL。也许这会破坏它?使用URL.createObjectURL(file)
而不是使用FileReader的可能重复项