metro下用WinJS请求网络图片并保存在应用程序的LocalState文件夹下。
var applicationData = Windows.Storage.ApplicationData.current; var localFolder = applicationData.localFolder; var dirctoryImgFolder="images\\";//保存图片的文件夹 function imgPromise(picUrl) { var picName = picUrl.substring(picUrl.lastIndexOf('/') + 1, picUrl.length); //从url截取图片名称 var picFile; //1创建文件 //2请求数据 //3保存数据 return createFile(dirctoryImgFolder + picName).then(function (file) { picFile = file; }).then(function () { return WinJS.xhr({ url: picUrl, responseType: "blob" });//请求网络图片 }).then(function complete(result) { if (result.status === 200) { console.log(picUrl + " 图片下载成功"); return writeBuffer(picFile, result.response); } }, function onError() { console.log(picUrl + " ---图片下载失败---"); }); } //创建文件 function createFile(fileName) { return localFolder.createFileAsync(fileName, Windows.Storage.CreationCollisionOption.replaceExisting); } //将图片的blob数据保存到文件 function writeBuffer(file, blob) { return file.openAsync(Windows.Storage.FileAccessMode.readWrite).then(function (output) { // Get the IInputStream stream from the blob object var input = blob.msDetachStream(); // Copy the stream from the blob to the File stream return Windows.Storage.Streams.RandomAccessStream.copyAsync(input, output).then(function () { output.flushAsync().done(function () { input.close(); output.close(); console.log("File '" + file.name + "' saved successfully '"); }, function () { console.log("保存失败");}); }, function () { console.log("保存失败"); }); }, function () { console.log("保存失败"); }); }
直接调用imgPromise方法传入图片url,即可将图片下载到程序的localstate下。
对于多幅图片可用WinJS.Promise.join()方法传入promise数组从而汇总结果。
var directoryImgPromises = [];//下载图片的promise数组
directoryImgPromises.push(imgPromise("图片url"));//下载左侧大图
//汇总下载结果
WinJS.Promise.join(directoryImgPromises).then(function allComplete() {
console.log("所有下载操作执行成功");
}, function hasError() {
console.log("所有下载操作执行有失败");
}).done(function () {
//成功回调
callback();//自定义回掉函数
});