I serialized my Image like Uri and I have trouble with Deserialization
var storageFile = await StorageFile.GetFileFromPathAsync(temp[0].BackStage.AbsoluteUri);
using (var stream = await storageFile.OpenReadAsync())
{
await BackStageImg.SetSourceAsync(stream);
}
This code doesnt work, it says "You dont have an access" when I try put Uri to StorageFile
I copied my file to App Local Folder and pick like
StorageFile localFile = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appdata:///local/background"));
Related
I've been trying to get uploading an image anonymously onto Imgur using the Imgur API to work, however I've been facing an issue with unauthorized path access.
I've tried search around other similar articles on Microsoft Docs and posts here on stack overflow but couldn't find a solution. I've even given my application "broadFileSystemAccess" as rescap capability in my Package.appxmanifest which I found from reading the Microsoft UWP documentations.
The error I receive is:
System.UnauthorizedAccessException: 'Access to the path 'C:\Users\lysyr\Pictures\ROG Logo.png' is denied.'
The error occurs at the var filecon = File.ReadAllBytes(imgpath); line.
My File Picker code is:
public static string imgpath = "";
public static string finalimg = "";
private async void FileNameButton_Click(object sender, RoutedEventArgs e)
{
var picker = new Windows.Storage.Pickers.FileOpenPicker();
picker.ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail;
picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.PicturesLibrary;
picker.FileTypeFilter.Add(".jpg");
picker.FileTypeFilter.Add(".jpeg");
picker.FileTypeFilter.Add(".png");
Windows.Storage.StorageFile file = await picker.PickSingleFileAsync();
if (file != null)
{
// Application now has read/write access to the picked file
imgpath = file.Path;
var filecon = File.ReadAllBytes(imgpath); #Error drops here <---
finalimg = Convert.ToBase64String(filecon);
await ImgurUploadAPI();
Debug.WriteLine("Picked Image: " + file.Name);
uploadedimage_text.Text = "Picked Image: " + file.Name;
}
else
{
Debug.WriteLine("Image uploading has been cancelled.");
}
}
And the ImgurUpload task code is:
public static string imgurlink = "";
public async Task ImgurUploadAPI()
{
try
{
if (imgpath != null)
{
// Construct the HttpClient and Uri
HttpClient httpClient = new HttpClient();
Uri uri = new Uri("https://api.imgur.com/3/upload");
httpClient.DefaultRequestHeaders.Add("Authorization", "Client-ID IMGUR-CLIENTIDHERE");
//Debug.WriteLine("Request Headers: ");
// Construct the JSON to post
HttpStringContent content = new HttpStringContent("image=\"{finalimg}\"");
Debug.WriteLine("Request Upload: " + content);
// Post the JSON and wait for a response
HttpResponseMessage httpResponseMessage = await httpClient.PostAsync(
uri,
content);
// Make sure the post succeeded, and write out the response
httpResponseMessage.EnsureSuccessStatusCode();
var httpResponseBody = await httpResponseMessage.Content.ReadAsStringAsync();
imgurlink = httpResponseBody;
Debug.WriteLine("Request Response: " + httpResponseBody);
}
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
}
I feel like it might be something to do with the way I access and convert the image to be ready for upload. Any tips would be very appreciated as I've been stuck on this for awhile now and it's one of the last things I need to complete for my project. Cheers!
Besides #Julian Silden Langlo answer. there is another option for your scenario. The reason for this behavior is that you could not directly access the file using File.ReadAllBytes(String) Method.
I noticed that you've already added the broadFileSystemAccess capability, what you need to note is that this capability only works for the Windows.Storage APIs. So you could only use it like
StorageFile file = StorageFile.GetFileFromPathAsync(filepath)
When you use UWP your access to the file system is limited. This means that you can't simply read a file at an arbitrary path like you're trying to do here:
var filecon = File.ReadAllBytes(imgpath);
What you need to do instead is to ask the StorageFile object you received from the FilePicker for a read Stream. Like so:
var buffer = await FileIO.ReadBufferAsync(file);
var filecon = buffer.ToArray();
finalimg = Convert.ToBase64String(filecon);
You can find more information about file access for UWP at Microsoft Docs.
I have found some answers here that give examples but none seems to work for me..
this is how my postman looks:
In the code I download the picture from a URL, save it as jpeg inside a folder and then I try to upload that image with a POST request, here is how it looks:
var fileName = image.PhotoId + ".jpeg";
await Task.WhenAll(client.DownloadFileTaskAsync(new Uri(image.ImageUrl), #"wwwroot\images\"+fileName));
var files = Directory.GetFiles(#"wwwroot\images\", "*.jpeg");
var filePath = Path.Combine(#"wwwroot\images\", fileName);
using var stream = File.OpenRead(filePath);
var file_content = new ByteArrayContent(new StreamContent(stream).ReadAsByteArrayAsync().Result);
var formData = new MultipartFormDataContent();
formData.Add(file_content, "file", fileName);
var res = await clientAsync.PostAsync(url, formData);
problem is the response that I get in the code is an error..:
{"error_code":6,"error_message":"Sorry, please try a different picture"}
this type of response is the same one I get when trying to upload a pdf instead of a jpeg on postman so I guess the file is getting corrupted in the code somewhere.
would love to get any ideas to where the problem is!
I am working on a Windows to UWP app. A web service exists that when called (GET), returns a file. When the web service is triggered using a browser, it successfully downloads a file on the browser.
On the UWP app, I am using Windows.Web.Http to call the web service. I need to save get the file sent by the web service and save it on the device.
I currently have the following code. Not sure how to get the result from the web service and save to the file.
public async Task DownloadFile(string WebServiceURL, string PathToSave)
{
var myFilter = new Windows.Web.Http.Filters.HttpBaseProtocolFilter();
myFilter.AllowUI = false;
Windows.Web.Http.HttpClient client = new Windows.Web.Http.HttpClient(myFilter);
Windows.Web.Http.HttpResponseMessage result = await client.GetAsync(new Uri(WebServiceURL));
using (IInputStream inputStream = await result.Content.ReadAsInputStreamAsync())
{
//not sure if this is correct and if it is, how to save this to a file
}
}
Using System.Web.Http, I am able to easily do this using the following:
Stream stream = result.Content.ReadAsStreamAsync().Result;
var fileStream = File.Create(PathToSave);
await stream.CopyToAsync(fileStream);
fileStream.Dispose();
stream.Dispose();
However, using Windows.Web.Http, I am not sure how I can do this. Please help!
this what you looking for?
like this?
var myFilter = new Windows.Web.Http.Filters.HttpBaseProtocolFilter();
myFilter.AllowUI = false;
Windows.Web.Http.HttpClient client = new Windows.Web.Http.HttpClient(myFilter);
Windows.Web.Http.HttpResponseMessage result = await client.GetAsync(new Uri(WebServiceURL));
//not sure if this is correct and if it is, how to save this to a file
var file = await ApplicationData.Current.LocalFolder.CreateFileAsync("filename.tmp", CreationCollisionOption.GenerateUniqueName);
using (var filestream = await file.OpenAsync(FileAccessMode.ReadWrite))
{
await result.Content.WriteToStreamAsync(filestream);
await filestream.FlushAsync();
}
I have only file Uri to open in the MediaElement.
How to use _MediaElement.SetSource with Uri? My way is based on this example:
var file = await openPicker.PickSingleFileAsync();
var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
mediaControl.SetSource(stream, file.ContentType);
But, I have only Uri from the file. Any ideas?
If you have the Uri, you should use the Source property on the MediaElement:
mediaControl.Source = myUri;
SetSource is more appropriate if you have a stream object.
I'm using the following code to download an image from a url
HttpClient client = new HttpClient();
var stream = await client.GetStreamAsync(new Uri("<your url>"));
var file = await KnownFolders.PictureLibrary.CreateFileAsync("myfile.png");
using (var targetStream = await file.OpenAsync(FileAccessMode.ReadWrite))
{
using (stream)
await stream.CopyToAsync(targetStream.AsStreamForWrite());
}
several users have reported that it doesn't always download the entire image. That they sometimes get partial images and the rest is just garbage.
Is there any reason for this?
Thanks!
I would suggest trying the WebClient class with the DownloadData or DownloadDataAsync method.
File.WriteAllBytes("myfile.png",
new WebClient().DownloadData("<your url>"));
edit If the stream is giving you trouble you could use the byte array response instead. Your "using" statement with async code inside may be causing it to dispose early, perhaps?
var httpClient = new HttpClient();
var data = await httpClient.GetByteArrayAsync(new Uri("<Your URI>"));
var file = await KnownFolders.PictureLibrary.CreateFileAsync("myfile.png");
var targetStream = await file.OpenAsync(FileAccessMode.ReadWrite)
await targetStream.AsStreamForWrite().WriteAsync(data, 0, data.Length);
targetStream.FlushAsync().Wait();
targetStream.Close();
BackgroundDownloader is the easiest way to download a file.
using Windows.Storage;
public async Task DownloadPhoto(Uri uri)
{
var folder = ApplicationData.Current.LocalFolder;
var photoFile = await folder.CreateFileAsync("photo.jpg", CreationCollisionOption.ReplaceExisting);
var downloader = new Windows.Networking.BackgroundTransfer.BackgroundDownloader();
var dl = downloader.CreateDownload(uri, photoFile);
await dl.StartAsync();
}
If your using HttpClient then if your image is larger than 64K it will error out. You will have to set the httpClient.MaxResponseContentBufferSize to something larger.
See the MSDN Quick Start where they set the max-buffer-size to 256K.
http://msdn.microsoft.com/en-us/library/windows/apps/xaml/JJ152726(v=win.10).aspx
Personally though, I use the BackgroundDownloader.