I have been trying to download an image from an url to local file system using cordova 3.8 on Windows Phone.
I want to store pictures and be able to use them in the HTML view.
I am using the file transfer and the file system plugins :
I have been playing around with both, but without success. I think the problem comes from the target file URI, as I have not found any way of getting the download folder path.
I can easily read and write text files using the examples in the cordova-file plugin's documentation, but I do not find anything on how to get the directory's path in order to pass it to the file transfer plugin.
Any idea ? I am testing on WP8.
You can make your own plugin(I can explain how if needed) and use MediaLibrary.SavePicture method. Put this in your plugin class:
public static byte[] ReadFully(Stream input)
{
byte[] buffer = new byte[16 * 1024];
using (MemoryStream ms = new MemoryStream())
{
int read;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
return ms.ToArray();
}
}
public void SavePicture(string options)
{
string[] optString = getOptionStrings(options);
string url = optString[0];
string callbackId = optString[1];
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.BeginGetResponse(new AsyncCallback((result) =>
{
try
{
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result);
byte[] content = ReadFully(response.GetResponseStream());
MediaLibrary lib = new MediaLibrary();
lib.SavePicture("Test Picture", content);
DispatchCommandResult(new PluginResult(PluginResult.Status.OK), callbackId);
}
catch (Exception e)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, e), callbackId);
}
}), null);
}
And call it like this:
cordova.exec(function (result) {
// success
}, function (e) {
// error
}, 'YourPluginClass', 'SavePicture', [yourUrl]);
NOTE: You must have ID_CAP_MEDIALIB_PHOTO capability checked in the manifest.