繁体   English   中英

尝试在C#UWP中的imgur上上传图像

[英]Trying to upload an image on imgur in c# UWP

我是C#的新手,我正在使用imgurAPI做一个应用程序。 我正在尝试在上面上传图像,但是在读取文件时似乎出现了问题。 真的不知道该怎么办。 (错误不是来自Oauth或访问令牌等)

这是我使用的功能。 第一个是单击上传按钮时调用的名称。

public async void FileNameButton_Click()
    {
        try
        {
            Debug.WriteLine("ICI");
            FileOpenPicker fileOpenPicker = new FileOpenPicker();
            fileOpenPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
            fileOpenPicker.ViewMode = PickerViewMode.Thumbnail;
            fileOpenPicker.FileTypeFilter.Add(".png");
            fileOpenPicker.FileTypeFilter.Add(".jpeg");
            fileOpenPicker.FileTypeFilter.Add(".jpg");
            fileOpenPicker.FileTypeFilter.Add(".gif");

            StorageFile file = await fileOpenPicker.PickSingleFileAsync();
            if (file != null)
            {

                _path = file.Path;
                await UploadImage();
                Debug.WriteLine(file.Path);
            }
        }
        catch (Exception exception)
        {
            Debug.WriteLine(exception.Message);
        }
    }

_

public async Task UploadImage()
    {
        Debug.WriteLine("UPLOADIMAGE");
        try
        {
            if (_path != null)
            {
                Debug.WriteLine("String to upload " + _path); 
                //_path is ok here, form is         "C:\Users\MyName\Pictures\1412091183-dreamfall-chapters.jpg"

                var endpoint = new ImageEndpoint(SimpleIoc.Default.GetInstance<ImgurApi>()._Client);
                try
                {
                    var file = File.ReadAllBytes(_path);
                    var image = await endpoint.UploadImageBinaryAsync(file);
                }
                catch (Exception message)
                {
                    Debug.WriteLine(message);
                }

            }
        }
        catch (Imgur.API.ImgurException imgurEx)
        {
            Debug.Write("An error occurred uploading an image to Imgur.");
            Debug.Write(imgurEx.Message);
        }
    }

这是我得到的错误:

引发异常:System.IO.FileSystem.dll中的“ System.InvalidOperationException” System.InvalidOperationException:不应在UI线程上执行同步操作。 考虑将此方法包装在Task.Run中。 位于System.IO.WinRTFileSystem.Open(位于System.IO.WinRTFileSystem.EnsureBackgroundThread()处(字符串fullPath,FileMode模式,FileAccess访问,FileShare共享,Int32 bufferSize,FileOptions选项,FileStream父级)路径,FileMode模式,FileAccess访问,FileShare共享,Int32 bufferSize,FileOptions选项)位于Epicture.ViewModels.MainPageVm.d__19.MoveNext()处System.IO.File.InternalReadAllBytes(字符串路径)C:\\ Users \\ Bandini \\ Pictures \\ 1412091183 - 梦陨-chapters.jpg

提前致谢。

您正在使用File.ReadAllBytes ,这是一个同步调用,它将阻止UI线程。

您应该为此使用aync IO API。

ImageEndpoint也具有接受流的方法,这是更可取的。

例:

using(var file = File.OpenRead(_path))
{
    var image = await endpoint.UploadImageStreamAsync(file);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM