How to convert String to FileImage in Flutter? - firebase

I have saved images as FileImage in my docs. i want to upload them to firebase storage. But it throws the error that type String can not be converted into type File.
here is my code.
String localImage = gg['path1']['path2']['path3'];//this is actually a fileimage inform of a string
File ll = File(localImage);
String downloadUrl = await FirebaseStorageHelper()
.uploadImageAndGetDownloadUrl(
image: ll, uid: FirebaseAuth.instance.currentUser.uid);
}
Update, i tried this code. But it throws existsSync Error
FileImage localImage =
FileImage(io.File(gg['path1']['path2]['path3']));
print(localImage.file.absolute.existsSync());
Please help, I couldn't find anything useful on google

Try this.
it may be because you haven't converted it into a uri.
Uri myUri = Uri.parse(gg['path1']['path2']['path3']);
File ff = File.fromUri(myUri);

Related

Getting files on iOS

I am creating json files FileSystem.AppDataDirectory, "test"," {Hour}.json "; I can see the files on the device in Xcode.. once I return only one with this Path.Combine(FileSystem.AppDataDirectory, "test",".json") then I can read its content.
However once I need to return all files from the directory and list the path to them in my application
var result = Directory.EnumerateFiles(FileSystem.AppDataDirectory, "test");
The result is empty
this is the path /var/mobile/Containers/Data/Application/02A91048-0016-4E20-A8A6-EB2A89649F1F/Library
which is correct an I see the files the physical. Where am I doing mistake?
I have also tried this
var test = FileSystem.OpenAppPackageFileAsync(FileSystem.AppDataDirectory);
but I am getting unauthorized exception
you are looking for files in the test subfoloder
the signature of EnumerateFiles is
public static System.Collections.Generic.IEnumerable<string> EnumerateFiles (string path, string searchPattern);
so you want to do this
var path = Path.Combine(FileSystem.AppDataDirectory,"test");
var result = Directory.EnumerateFiles(path, "*.json");

Xamarin.Forms: DirectoryNoFoundException on WritingBytes

i download a video from a server as bytes and write those bytes as mp4 to the phones harddrive in pcl:
byte[] stream = await VideoAPI.DownloadVideo(AdID);
File.WriteAllBytes("/storage/emulated/0/Android/data/com.companyname.interiorcircle/files/Movies/file.mp4", stream);
But this returns the following error:
(stream is not null)
{System.IO.DirectoryNotFoundException: Could not find a part of the path "/storage/emulated/0/Android/data/com.companyname.interiorcircle/files/Movies/file.mp4".
But that doesnt make sense, since I am writing the file and path.
Where is this error comming from?
(Wiredly enough, while testing this worked once, but then not again)
Thank you!
use the Environment.SpecialFolder to create a path, not a string variable.
byte[] stream = await VideoAPI.DownloadVideo(AdID);
string fullPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "file.mp4"); //also you can create extra folders
File.WriteAllBytes(fullPath , stream);
also, you can use different folders such as;
Environment.SpecialFolder.MyVideos
Environment.SpecialFolder.Personel
Environment.SpecialFolder.ApplicationData
Environment.SpecialFolder.Templates
Environment.SpecialFolder.CommonApplicationData
Environment.SpecialFolder.MyMusic
Environment.SpecialFolder.MyPictures
Environment.SpecialFolder.Fonts
Environment.SpecialFolder.MyDocuments
Environment.SpecialFolder.Desktop

Error 500 when replacing file in Azure Blob Storage

Good day, I'm having an error where when I replace a file, it returns "500 internal server error". But when I upload a new file everything is okay.
Here is my code:
public async Task UploadContentBlobAsync(IFormFile formFile, string fileName)
{
var blobClient = _containerClient.GetBlobClient(fileName);
await blobClient.UploadAsync(formFile.OpenReadStream());
}
accoring to this source Azure will just replace my fie to be uploaded to the existing file, but that doesn't happen to my case.
I am using Azure.Storage.Blobs 12.4.3, I create a method and pass the request as a parameter. The following code works and no error will be reported during the replacement of blob content:
string connectionString = "DefaultEndpointsProtocol=https;AccountName=0730bowmanwindow;AccountKey=xxxxxx;EndpointSuffix=core.windows.net";
string containerName = "video";
string fileName = "1.png";
BlobServiceClient blobServiceClient = new BlobServiceClient(connectionString);
BlobContainerClient containerClient = blobServiceClient.GetBlobContainerClient(containerName);
BlobClient blobClient = containerClient.GetBlobClient(fileName);
await blobClient.UploadAsync(req.Body, true);
(I put the picture in the binary format and put it in the request.)
In the package I use, the Boolean value of parameter of the UploadAsync method about whether to override blob is false, so I must provide a true, otherwise it will report an error.
You can make an experiment to see if it can be executed correctly according to the package version and code provided by me. If not, please provide detail error information.:)

How to convert the ImageSource.FromFile to stream in Xamarin.Forms?

I want to convert Image to stream from the ImageSource.FromFile.
My Code:
string location = Path.Combine(FileSystem.AppDataDirectory, "data", "Demo.jpg");
image.Source = ImageSource.FromFile(location);
The image is shown properly but I want to convert this image to Stream in Forms.UWP.
I tried the await StorageFile.GetFileFromApplicationUriAsync() this code to get the stream of the image from the location but it throws an exception.
Please suggest me how to convert the image from the file to stream in UWP?
Santhiya A
This path Path.Combine(FileSystem.AppDataDirectory, "data", "Demo.jpg"); is app's local path within UWP platform. And it is not app installation path. if place the Demo.jpg in your project folder, you will not find it with above path. And the parameter of ImageSource.FromFile(string file) is file name, but not the complete path. For the detail please refer this case reply.
I tried the await StorageFile.GetFileFromApplicationUriAsync() this code to get the stream of the image from the location but it throws an exception.
For UWP platform, you could use the following to converter the image file(build property is Content) to steam. For more please refer this document.
private async Task<Stream> GetStreamAsync()
{
var file = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/Demo.jpg"));
var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
return stream.AsStream();
}
And if you want use above in Xamarin Forms client project, you need package above method with DependencyService.

Uploading files to Blob & getting error: C:\Program Files (x86)\IIS Express\

I tried to upload file to blob. But I'm getting error like this:
"'C:\Program Files (x86)\IIS
Express\Nominative-Officers-Entry-Form-Stu.docx'."
I don't use HttpPostedFileBase in my code. I just pass object to my controller with files to be uploaded. Lease tell me what I'm doing wrong?
I want to know wt this line means :
"blockBlob.Properties.ContentType = "
This is my code:
public static SaveResponses CreateFile(Blob_Storage_Header docDetails)
{
string storageConnectionString = ConfigurationManager.ConnectionStrings["StorageConnectionString"].ConnectionString.ToString();
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(storageConnectionString);
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
CloudBlobContainer container = blobClient.GetContainerReference("test2");
ICollection<Blob_Storage_Details> BlobStorageDetails = docDetails.Blob_Storage_Details;
if (BlobStorageDetails.Count > 0) {
foreach (Blob_Storage_Details item in BlobStorageDetails)
{
string DocUUID = Guid.NewGuid().ToString();
CloudBlockBlob blockBlob = container.GetBlockBlobReference(DocUUID + item.Blob_Name);
var fileName = Path.GetFileName(item.Blob_Name);
//blockBlob.Properties.ContentType = item.ContentType;
// Create or overwrite the "myblob" blob with contents from a local file.
using (var fileStream = File.OpenRead(fileName))
{
blockBlob.UploadFromStream(fileStream);
}
}
}
SaveResponses saveResponse = new SaveResponses();
saveResponse.saveStatus = "true";
saveResponse.messageType = "success";
saveResponse.message = "File Create message";
return (saveResponse);
}
"'C:\Program Files (x86)\IIS Express\Nominative-Officers-Entry-Form-Stu.docx'."
Based on your code, I ran it on my side, then I got the following error:
Remark: In development environment, you could add “<customErrors mode="Off"/>” within the system.web node in your Web.config file, then you could view the detailed errors.
According to this error, I checked and found the specified file path was not existed.
After some trials, I fixed the issue on my side. Please follow the descriptions below to check your code to see whether it works:
a) Please pay attention to the code “Path.GetFileName”, it returns the file name and extension of the specified path string (e.g. settings.job).
b) Make sure that the filename that is used in “File.OpenRead(fileName)” is an absolute file path and the file is existed in your environment.
"blockBlob.Properties.ContentType = "
Azure Storage Client Library for .NET is based on Storage Service REST API,
From the official document we could find that “blockBlob.Properties.ContentType” represents the MIME content type of the blob, the default type is application/octet-stream.
MIME is a way to identity files on internet according to their nature and format. For example, using the "Content-type" header value defined in a HTTP response, the browser can open the file with the proper extension/plugin. For more details about MIME, please refer to this link: http://www.freeformatter.com/mime-types-list.html

Resources