将图像上传到 Imgur API - C# UWP

Upload an image onto Imgur API - C# UWP

我一直在尝试使用 Imgur API 将图像匿名上传到 Imgur 上,但我一直面临未经授权的路径访问问题。

我尝试搜索 Microsoft Docs 上的其他类似文章,并在此处发布有关堆栈溢出的文章,但找不到解决方案。我什至在我的 Package.appxmanifest 中将我的应用程序“broadFileSystemAccess”作为重新捕获功能,这是我通过阅读 Microsoft UWP 文档发现的。

我收到的错误是:

System.UnauthorizedAccessException: 'Access to the path 'C:\Users\lysyr\Pictures\ROG Logo.png' is denied.'

错误发生在 var filecon = File.ReadAllBytes(imgpath); 行。

我的文件选择器代码是:

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.");
        }
    }

而 ImgurUpload 任务代码为:

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);
        }
    }

我觉得这可能与我访问和转换图像以准备上传的方式有关。任何提示将不胜感激,因为我已经坚持了一段时间,这是我需要为我的项目完成的最后一件事。干杯!

当您使用 UWP 时,您对文件系统的访问受到限制。这意味着您不能像在这里尝试做的那样简单地读取任意路径的文件:

var filecon = File.ReadAllBytes(imgpath);

您需要做的是向您从 FilePicker 收到的 StorageFile 对象请求读取流。像这样:

var buffer = await FileIO.ReadBufferAsync(file);
var filecon = buffer.ToArray();
finalimg = Convert.ToBase64String(filecon);

您可以在 Microsoft Docs.

找到有关 UWP 文件访问的更多信息

除了@Julian Silden Langlo 的回答。您的方案还有另一种选择。出现此行为的原因是您无法使用 File.ReadAllBytes(String) Method.

直接访问该文件

我注意到您已经添加了 broadFileSystemAccess 功能,您需要注意的是此功能仅适用于 Windows.Storage API。所以你只能像

那样使用它
StorageFile file = StorageFile.GetFileFromPathAsync(filepath)