Upload image to local storage in Metro style apps

In WinRT / C #, how do I upload an image to a local folder to support caching of an online directory for offline use? Is there a way to directly download images and link the control to get them from the cache as a backup?

    var downloadedimage = await HttpWebRequest.Create(url).GetResponseAsync();
    StorageFile imgfile = await ApplicationData.Current.LocalFolder.CreateFileAsync(
                        "localfile.png", CreationCollisionOption.FailIfExists);

What should I do next to save the uploaded image as localfile.jpg?

+5
source share
5 answers

It looks like the code below from the HttpClient example for Windows 8 solves the problem

    HttpRequestMessage request = new HttpRequestMessage(
        HttpMethod.Get, resourceAddress);
    HttpResponseMessage response = await rootPage.httpClient.SendAsync(request,
        HttpCompletionOption.ResponseHeadersRead);

httpClient HttpClient, . , ( , )

    InMemoryRandomAccessStream randomAccessStream = 
        new InMemoryRandomAccessStream();
    DataWriter writer = new DataWriter(randomAccessStream.GetOutputStreamAt(0));
    writer.WriteBytes(await response.Content.ReadAsByteArrayAsync());
    await writer.StoreAsync();
    BitmapImage image = new BitmapImage();
    imagecontrol.SetSource(randomAccessStream);

,

    var imageFile = await ApplicationData.Current.LocalFolder.CreateFileAsync(
         filename, CreationCollisionOption.ReplaceExisting);
    var fs = await imageFile.OpenAsync(FileAccessMode.ReadWrite);
    DataWriter writer = new DataWriter(fs.GetOutputStreamAt(0));
    writer.WriteBytes(await response.Content.ReadAsByteArrayAsync());
    await writer.StoreAsync();
    writer.DetachStream();
    await fs.FlushAsync();
+10

:

        var response = await HttpWebRequest.Create(url).GetResponseAsync();
        List<Byte> allBytes = new List<byte>();
        using (Stream imageStream = response.GetResponseStream())
        {
            byte[] buffer = new byte[4000];
            int bytesRead = 0;
            while ((bytesRead = await imageStream.ReadAsync(buffer, 0, 4000)) > 0)
            {
                allBytes.AddRange(buffer.Take(bytesRead));
            }
        }
        var file = await ApplicationData.Current.LocalFolder.CreateFileAsync(
                    "localfile.png", CreationCollisionOption.FailIfExists);
        await FileIO.WriteBytesAsync(file, allBytes.ToArray()); 
+3

, URL-, - BackgroundDownloader. . , .

+1

GetResponseAsync WebResponse, :

Stream imageStream = downloadedimage.GetResponseStream();

:

byte[] imageData = new byte[imageStream.Length];
using(StreamReader reader = new Streamreader(imageStream))
{
    reader.ReadBytes(imageData, 0, imageData.Length);
}
await FileIO.WriteBytesAsync(imgfile, imageData);
0

By default, bitmaps are cached by WinRT without the intervention required by the developer.

0
source

All Articles