下载图像并显示图像时出现问题

bwntbbo3  于 2021-09-13  发布在  Java
关注(0)|答案(2)|浏览(530)

当我点击图像时,它会下载并存储在一个特殊的文件夹中,然后在gallery应用程序中打开。但是第一次,第二次我点击它时,它捕捉到一个错误:它显示正确。。。
我该如何解决这个问题?
查看视频以获取解释。
视频(gif格式)
下载图像的代码。

public async Task DownloadImage(string URL)
{
    WebClient webClient = new WebClient();

    string folderPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "Images", "temp");
    string fileName = URL.ToString().Split('/').Last();
    string filePath = Path.Combine(folderPath + "/", fileName);

    webClient.DownloadDataCompleted += (s, e) =>
    {
        byte[] bytes = new byte[e.Result.Length];
        bytes = e.Result; // get the downloaded data
        File.WriteAllBytes(filePath, bytes);
    };

    webClient.DownloadDataAsync(new Uri(URL));

    Preferences.Set("filePath", filePath);
}

执行上述函数的代码:

Image imagen = new Image
{
                    Source = url + Foto.ID_Parte + "/" + Foto.Archivo
};
var imagen_tap = new TapGestureRecognizer();
imagen_tap.Tapped += async (s, e) =>
{
    string urlImage = url + Foto.ID_Parte + "/" + Foto.Archivo;
    await api.DownloadImage(urlImage);
    string path = Preferences.Get("filePath", "");
    try
    {
        await Launcher.OpenAsync(new OpenFileRequest { File = new ReadOnlyFile(path) });
    }
    catch
    {
        await DisplayAlert("Error", "No se ha encontrado la imagen:" + path, "Cerrar");
    }
};

imagen.GestureRecognizers.Add(imagen_tap);

编辑:例外情况给出:

EXCEPTION:::::: System.IO.FileNotFoundException: Could not find file "/data/user/0/com.companyname.workersapp/files/Images/temp/2021072010242814266200.jpg"
File name: '/data/user/0/com.companyname.workersapp/files/Images/temp/2021072010242814266200.jpg'
  at System.IO.FileStream..ctor (System.String path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share, System.Int32 bufferSize, System.Boolean anonymous, System.IO.FileOptions options) [0x001aa] in /Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/mcs/class/corlib/System.IO/FileStream.cs:239 
  at System.IO.FileStream..ctor (System.String path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share, System.Int32 bufferSize, System.IO.FileOptions options) [0x00000] in /Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/mcs/class/corlib/System.IO/FileStream.cs:106 
  at (wrapper remoting-invoke-with-check) System.IO.FileStream..ctor(string,System.IO.FileMode,System.IO.FileAccess,System.IO.FileShare,int,System.IO.FileOptions)
  at System.IO.FileSystem.CopyFil07-26 12:42:47.751 V/mono-stdout(22224):   at System.IO.FileSystem.CopyFile (System.String sourceFullPath, System.String destFullPath, System.Boolean overwrite) [0x00025] in /Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/external/corefx/src/System.IO.FileSystem/src/System/IO/FileSystem.Unix.cs:54 
  at System.IO.File.Copy (System.String sourceFileName, System.String destFileName, System.Boolean overwrite) [0x00056] in /Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/external/corefx/src/System.IO.FileSystem/src/System/IO/File.cs:74 
  at Xamarin.Essentials.Platform.GetShareableFileUri (Xamarin.Essentials.FileBase file) [0x0002c] in D:\a\1\s\Xamarin.Essentials\Platform\Platform.android.cs:107-26 12:42:47.752 V/mono-stdout(22224):   at Xamarin.Essentials.Platform.GetShareableFileUri (Xamarin.Essentials.FileBase file) [0x0002c] in D:\a\1\s\Xamarin.Essentials\Platform\Platform.android.cs:151 
  at Xamarin.Essentials.Launcher.PlatformOpenAsync (Xamarin.Essentials.OpenFileRequest request) [0x00000] in D:\a\1\s\Xamarin.Essentials\Launcher\Launcher.android.cs:41 
  at Xamarin.Essentials.Launcher.OpenAsync (Xamarin.Essentials.OpenFileRequest request) [0x00021] in D:\a\1\s\Xamarin.Essentials\Launcher\Launcher.shared.cs:50 
  at WorkersApp.Pageviews.DatosParte+<>c__DisplayClass16_0.<.ctor>b__3 (System.Object s, System.EventArgs e) [0x00110] in C:\Users\CGarcia\source\repos\WorkersApp\WorkersApp\WorkersApp\Pageviews\DatosParte.xaml.cs:101

第101行是:

await Launcher.OpenAsync(new OpenFileRequest { File = new ReadOnlyFile(path) });
qeeaahzv

qeeaahzv1#

原因 DownloadDataAsync 是一个同步方法,它通过回调返回数据 DownloadDataCompleted ,因此,当您第一次点击图像时,它会打开未完全下载的文件。

解决方案

代替 DownloadDataAsync 具有 DownloadDataTaskAsync ,在这种情况下,我们不需要 DownloadDataCompleted ,该方法将返回数据。

public async Task DownloadImage(string URL)
{
    WebClient webClient = new WebClient();

    string folderPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "Images", "temp");
    string fileName = URL.ToString().Split('/').Last();
    string filePath = Path.Combine(folderPath + "/", fileName);

    Preferences.Set("filePath", filePath);

    byte[] bytes = await webClient.DownloadDataTaskAsync(new Uri(""));
    File.WriteAllBytes(filePath, bytes);

}

将逻辑(打开文件)放入 DownloadDataCompleted ,这样可以确保文件完全下载。

public void DownloadImage(string URL)
{
    WebClient webClient = new WebClient();

    string folderPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "Images", "temp");
    string fileName = URL.ToString().Split('/').Last();
    string filePath = Path.Combine(folderPath + "/", fileName);

    webClient.DownloadDataCompleted += (s, e) =>
    {
        byte[] bytes = new byte[e.Result.Length];
        bytes = e.Result; // get the downloaded data
        File.WriteAllBytes(filePath, bytes);

        //move to here
        await Launcher.OpenAsync(new OpenFileRequest { File = new ReadOnlyFile(filePath ) });

    };

    webClient.DownloadDataAsync(new Uri(URL));
}

imagen_tap.Tapped += (s, e) =>
{
    string urlImage = url + Foto.ID_Parte + "/" + Foto.Archivo;
    api.DownloadImage(urlImage);
};

就个人而言,第二种方式更值得推荐。

2ul0zpep

2ul0zpep2#

我能理解你的问题…第一次下载图片时出现的问题会导致错误。我已经使用内容解析器下载了图像。这可能对你有帮助
`
私有图像(bmp:位图){

var imageOutStream: OutputStream
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
        val values = ContentValues()
        //image name
        values.put(MediaStore.Images.Media.DISPLAY_NAME, "image.jpg");
        // image type
        values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
        //storage path
        values.put(MediaStore.Images.Media.RELATIVE_PATH, "DCIM/" + "Camera");

        val uri = requireContext().contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)
        imageOutStream = uri?.let { requireContext().getContentResolver().openOutputStream(it) }!!
    }

    else
    {
        //creating directory and saving
        val imagesDir =
            Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString()
        val image = File(imagesDir, "image.jpg")
        imageOutStream =  FileOutputStream(image);

    }
    //compreesing the image
    bmp.compress(Bitmap.CompressFormat.JPEG, 100, imageOutStream);
    Toast.makeText(requireContext(),"ImageSaved",Toast.LENGTH_LONG).show()
    imageOutStream.close();

}`

相关问题