我有一个要求,我必须从网络网址下载图像并将它们保存到图片库中的某些文件夹中。请注意,它是一个 jabvascript 应用程序 (winJS)。我尝试了一些示例,但没有成功。
下面是我尝试过的一些代码:
方法一:
var download = null;
var promise = null;
function DownloadFile(uriString, fileName) {
try {
// Asynchronously create the file in the pictures folder.
Windows.Storage.KnownFolders.picturesLibrary.createFileAsync(fileName, Windows.Storage.CreationCollisionOption.generateUniqueName).done(function (newFile) {
var uri = Windows.Foundation.Uri(uriString);
var downloader = new Windows.Networking.BackgroundTransfer.BackgroundDownloader();
// Create a new download operation.
download = downloader.createDownload(uri, newFile).startAsync().then(complete, error, progress);
// Start the download and persist the promise to be able to cancel the download.
promise = download.startAsync().then(complete, error, progress);
}, error);
} catch (err) {
// displayException(err);
}
};
方法2:
function downloadFile(uri) {
var localFolder = Windows.Storage.KnownFolders.picturesLibrary;
var thumbnail = Windows.Storage.Streams.RandomAccessStreamReference.createFromUri(Windows.Foundation.Uri(uri));
Windows.Storage.StorageFile.createStreamedFileFromUriAsync("photo.jpg", Windows.Foundation.Uri(uri), thumbnail).done(function (newFile) {
/* Your success and error handlers */
localFolder.createFileAsync("photo2.jpg", Windows.Storage.CreationCollisionOption.replaceExisting)
.then(function (file) {
newFile.copyAndReplaceAsync(file);
});
});
}
最佳答案
您可以这样做(并且不要忘记在 list 中声明访问图片库的能力):
function downloadFileAsync(targetUrl , fileName) {
return WinJS.xhr({
responseType: "blob",
type: "GET",
url: targetUrl,
}).then(function (response) {
var fileContents = response.response;
return Windows.Storage.KnownFolders.picturesLibrary.createFileAsync(fileName, Windows.Storage.CreationCollisionOption.replaceExisting).then(function (newFile) {
return newFile.openAsync(Windows.Storage.FileAccessMode.readWrite).then(function (stream) {
return Windows.Storage.Streams.RandomAccessStream.copyAsync(fileContents.msDetachStream(), stream).then(function () {
return stream.flushAsync().then(function () {
stream.close();
fileContents.msClose();
});
});
});
});
});
}
关于javascript - Windows 8 商店 javascript 应用程序,从网络下载并保存图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33869430/