Error 500 when replacing file in Azure Blob Storage - asp.net

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.:)

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

How to convert String to FileImage in Flutter?

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

POST method to upload file to Azure storage - what to return

I am creating an app where
user can upload the text file and then
find most used word and change that word in text and
show the changed text to the user.
if it is possible, I would like to
get the file’s text content before uploading when Post method is being called and save that content
so I add the “DownloadTextAsync()” method inside of the POST method, but it seems like I am calling this method to the wrong subject?
[HttpPost("UploadText")]
public async Task<IActionResult> Post(List<IFormFile> files)
{
string connectionString = Environment.GetEnvironmentVariable("mykeystringhere");
// Create a BlobServiceClient object which will be used to create a container client
BlobServiceClient blobServiceClient = new BlobServiceClient(connectionString);
//Create a unique name for the container
string containerName = "textdata" + Guid.NewGuid().ToString();
// Create the container and return a container client object
BlobContainerClient containerClient = await blobServiceClient.CreateBlobContainerAsync(containerName);
// Create a local file in the ./data/ directory for uploading and downloading
string localPath = "./data/";
string fileName = "textfiledata" + Guid.NewGuid().ToString() + ".txt";
string localFilePath = Path.Combine(localPath, fileName);
// Get a reference to a blob
BlobClient blobClient = containerClient.GetBlobClient(fileName);
// Open the file and upload its data
using FileStream uploadFileStream = System.IO.File.OpenRead(localFilePath);
await blobClient.UploadAsync(uploadFileStream, true);
uploadFileStream.Close();
string downloadFilePath = localFilePath.Replace(".txt", "DOWNLOAD.txt");
// Get the blob file as text
string contents = blobClient.DownloadTextAsync().Result;
//return the string
return contents;
//if (uploadSuccess)
// return View("UploadSuccess");
//else
// return View("UploadError");
}
The issues I am having are
I understood that ‘blobClient’ is the reference to the blob, where I can get the file’s data but this must be wrong?
Also it seems like I cannot use “CloudBlobContainer” nor the “CloudBlockBlob blob”. Is it because inside of the POST method, the blob has been just initialized and does not exist when these twos are executed?
Also when I test the POST method, the console throws “Refused to load the font '' because it violates the following Content Security Policy directive: "default-src 'none'". Note that 'font-src' was not explicitly set, so 'default-src' is used as a fallback.” which I googled but have no idea what it means?
I have tried different ways but keep getting CANNOT POST/“ But could not really find the solid anwers. Could this be related to my POST method?
I understood that ‘blobClient’ is the reference to the blob, where I
can get the file’s data but this must be wrong?
That's correct in a sense that you can use blobClient to perform operations on blob like upload/download etc. I am not sure why you say but this must be wrong.
Also it seems like I cannot use “CloudBlobContainer” nor the
“CloudBlockBlob blob”. Is it because inside of the POST method, the
blob has been just initialized and does not exist when these twos are
executed?
No, this is happening because you're using a newer version of SDK (version 12.x.x) and CloudBlobContainer and CloudBlockBlob are available in the older version of the SDK.
Also when I test the POST method, the console throws “Refused to load
the font '' because it violates the following Content Security Policy
directive: "default-src 'none'". Note that 'font-src' was not
explicitly set, so 'default-src' is used as a fallback.” which I
googled but have no idea what it means? I have tried different ways
but keep getting CANNOT POST/“ But could not really find the solid
anwers. Could this be related to my POST method?
Not sure why this is happening. You may want to ask a separate question for this and when you do, please include the HTML portion of your code as well.

FormRecognizer C# SDK with blob file - unsupported media type error

I am trying to use C# FormRecognizer SDK of Azure Cognitive Service. I have pdfs stored in Azure Blob and I need to extract text/tables from these pdf files using C# SDK.
I see that "AnalyzeWithCustomModelAsync" method takes "Stream" as input parameter, where it accepts only "FileStream" type. If I pass "MemoryStream" as input parameter type, I am getting following error:
{"value":{"error":{"code":"UnsupportedMediaType","message":"In case of HTML form data, the multipart request must contain a document with a media type of - 'application/pdf', 'image/jpeg' or 'image/png'."}},"formatters":[],"contentTypes":[],"statusCode":415}
Is there anyway where I can use my blob file directly, without needing to have those files saved locally?
Regards,
Madhu
The following code snippet works by getting an instance of the blob (into CloudBlockBlob class) and then loading it into the MemoryStream. Once you have that, you can pass that into Form Recognizer to analyze.
List<string> blobsToAnalyze = new List<string>();
// Get latest Form Recognizer training model ID
Guid aiTrainModelId = Guid.Empty;
ModelResult latestModel = await FormRecognizer.GetModelAsync(config, log);
if (latestModel != null)
aiTrainModelId = latestModel.ModelId;
// Iterate through all blobs
foreach (string strBlob in blobsToAnalyze)
{
CloudBlockBlob blob = blobContainer.GetBlockBlobReference(strBlob);
using (MemoryStream ms = new MemoryStream())
{
// Load blob into a MemoryStream object
await blob.DownloadToStreamAsync(ms);
// Send to Form Recognizer to analyze
AnalyzeResult results = await FormRecognizer.AnalyzeFormAsync(config, aiTrainModelId, ms, log);
searchResults = FormRecognizer.AnalyzeResults(config, tableClient, results, log);
}
}

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