I do not know if this is a bug or not, but I have made a Xamarin app, that will connect to Azure storage to upload a file.
It doesn't want to upload nd I get this error
Azure service, to upload the file
I made the same application, using a console app (for testing fester)
var path = Path.Combine(projectPath, "universal.txt");
var fullpath = Path.GetFullPath(path);
var FileName = Path.GetFileName(fullpath);
using (StreamWriter sw = new StreamWriter(fullpath)) {
sw.WriteLine("Hello I want to go to Universal tomorrow");
}
var AzureStorage = new BlobContainerClient(ConectionString, ContanerName);
var blob = AzureStorage.GetBlobClient(FileName);
await blob.UploadAsync(fullpath);
My file get uploaded to Azure
File in storage
Use these functions to upload a file from xamarin.
static CloudBlobContainer GetContainer(ContainerType containerType)
{
var account = CloudStorageAccount.Parse(Constants.StorageConnection);
var client = account.CreateCloudBlobClient();
return client.GetContainerReference(containerType.ToString().ToLower());
}
public static async Task<string> UploadFileAsync(ContainerType containerType, Stream stream)
{
var container = GetContainer(containerType);
await container.CreateIfNotExistsAsync();
var name = Guid.NewGuid().ToString();
var fileBlob = container.GetBlockBlobReference(name);
await fileBlob.UploadFromStreamAsync(stream);
return name;
}
OR
client = new BlobServiceClient(storageConnectionString);
containerClient = await client.CreateBlobContainerAsync(containerName);
blobClient = containerClient.GetBlobClient(fileName);
await containerClient.UploadBlobAsync(fileName, memoryStreamFile);
Related
I'm having an issue with .NET 6 framework regarding the uploading of image files to S3 using the AWS SDK.
When I POST to my endpoint running on a local IIES it works perfectly and I can see the generated file in S3 without any issues.
The problem is the following: After a serverless deployment to AWS Lambda, the same .NET Core endpoint that produced a perfect result in my local environment behaves way different when it's running on a lambda. when I try to open the image it shows a square dot at the center but no image.
I am using IFormFile and here is my code
public async Task<string> Upload(IFormFile formfile, string name)
{
var xbuilder = WebApplication.CreateBuilder();
var _AwsSetting = xbuilder.Configuration.GetSection("AwsCredentials").Get<AWSCredentials>();
var accessKey = _AwsSetting.AWSAccessKey;
var secretKey = _AwsSetting.AWSSecretAccessKey;
RegionEndpoint bucketRegion = RegionEndpoint.APSouth1;
var bucketName = _AwsSetting.AWSS3BucketName;
var location = $"{name + Path.GetExtension(formfile.FileName)}";
var contentType = formfile.ContentType;
var client = new AmazonS3Client(accessKey, secretKey, bucketRegion);
try
{
using (var stream = new MemoryStream())
{
await formfile.CopyToAsync(stream);
var putRequest = new PutObjectRequest()
{
Key = location,
BucketName = bucketName,
InputStream = stream,
CannedACL = S3CannedACL.PublicRead,
ContentType=contentType
};
await client.PutObjectAsync(putRequest);
string publicUrl = string.Empty;
publicUrl = $"https://{bucketName}.s3.{bucketRegion.SystemName}.amazonaws.com/{location}";
return publicUrl;
}
}
catch (Exception e)
{
throw e;
}
}
I am working on a project to move a blob from one container to another, using azure functions with C#, I have tried different ways to copy the file from one container to another, however it has only been possible to move the name and extension but when downloading or trying to access the file the content is 0 bytes.
This is the code currently implemented.
namespace TestInput
{
[StorageAccount ("BlobConnectionString")]
public class TestInput
{
[FunctionName("TestInput")]
public static void Run(
[BlobTrigger("test/{name}")] Stream myBlob,
[Blob("testoutput/{name}", FileAccess.Write)] Stream outputBlob,
string name,
ILogger log)
{
var accountName = Environment.GetEnvironmentVariable("AccountName");
var accountKey = Environment.GetEnvironmentVariable("AccountKey");
var cred = new StorageCredentials(accountName, accountKey);
var account = new CloudStorageAccount(cred, true);
var client = account.CreateCloudBlobClient();
var sourceContainer = client.GetContainerReference("test");
var sourceBlob = sourceContainer.GetBlockBlobReference($"{name}");
var destinationContainer = client.GetContainerReference("testoutput");
var destinationBlob = destinationContainer.GetBlockBlobReference($"{name}");
destinationBlob.UploadFromStream(myBlob);
sourceBlob.Delete(DeleteSnapshotsOption.IncludeSnapshots);
}
}
}
I would be grateful if you could tell me how to solve this problem or what parameter I am missing.
Please Check if the below code helps to copy a blob from one container to another using Azure Function:
Below is the .NET 6 Azure Function of type Blob Storage Trigger:
using System;
using System.IO;
using System.Threading.Tasks;
using Azure.Storage.Blobs;
using Microsoft.Azure.WebJobs;
using Microsoft.Extensions.Logging;
using Microsoft.WindowsAzure.Storage.Blob;
namespace KrishBlobTriggerAF1205
{
public class Function1
{
[FunctionName("Function1")]
public async Task RunAsync([BlobTrigger("dev/{name}", Connection = "AzureWebJobsStorage")]Stream myBlob, string name, ILogger log,
[Blob("staging/{name}", FileAccess.Write)] Stream outputBlob)
{
var srcconnectionString = Environment.GetEnvironmentVariable("AzureWebJobsStorage");
string sourceContainer = "source";
string targetContainer = "target";
string blobName = "blob-name.txt";
BlobServiceClient serviceClient = new BlobServiceClient(srcconnectionString);
BlobContainerClient sourceContainerClient = serviceClient.GetBlobContainerClient(sourceContainer);
BlobContainerClient targetContainerClient = serviceClient.GetBlobContainerClient(targetContainer);
BlobClient sourceBlobClient = sourceContainerClient.GetBlobClient(blobName);
BlobClient targetBlobClient = targetContainerClient.GetBlobClient(blobName);
log.LogInformation("Sending copy blob request....");
var result = await targetBlobClient.StartCopyFromUriAsync(sourceBlobClient.Uri);
log.LogInformation("Copy blob request sent....");
log.LogInformation("============");
bool isBlobCopiedSuccessfully = false;
do
{
log.LogInformation("Checking copy status....");
var targetBlobProperties = await targetBlobClient.GetPropertiesAsync();
log.LogInformation($"Current copy status = {targetBlobProperties.Value.CopyStatus}");
if (targetBlobProperties.Value.CopyStatus.Equals(CopyStatus.Pending))
{
System.Threading.Thread.Sleep(1000);
}
else
{
isBlobCopiedSuccessfully = targetBlobProperties.Value.CopyStatus.Equals(CopyStatus.Success);
break;
}
} while (true);
if (isBlobCopiedSuccessfully)
{
log.LogInformation("Blob copied successfully. Now deleting source blob...");
await sourceBlobClient.DeleteAsync();
}
}
}
}
Hello I have created a windows application which uploads image from hdd to google cloud server.
My code was working perfectly but after changing bucket name it is not working.
My both buckets are in the same project and I have given OAuth 2.0 to my project.
even there is no error showing while processing. Please help me.
string bucketForImage = ConfigurationManager.AppSettings["BucketName"];
string projectName = ConfigurationManager.AppSettings["ProjectName"];
string Accountemail = ConfigurationManager.AppSettings["Email"];
var clientSecrets = new ClientSecrets();
clientSecrets.ClientId = ConfigurationManager.AppSettings["ClientId"];
clientSecrets.ClientSecret = ConfigurationManager.AppSettings["ClientSecret"];
string gcpPath = #"D:\mrunal\tst_mrunal.png";
var scopes = new[] { #"https://www.googleapis.com/auth/devstorage.full_control" };
var cts = new CancellationTokenSource();
var userCredential = await GoogleWebAuthorizationBroker.AuthorizeAsync(clientSecrets, scopes, Accountemail, cts.Token);
var service = new Google.Apis.Storage.v1.StorageService();
var bucketToUpload = bucketForImage;
var newObject = new Google.Apis.Storage.v1.Data.Object()
{
Bucket = bucketToUpload,
Name = "mrunal.png"
};
fileStream = new FileStream(gcpPath, FileMode.Open);
var uploadRequest = new Google.Apis.Storage.v1.ObjectsResource.InsertMediaUpload(service, newObject,
bucketToUpload, fileStream, "image/png");
uploadRequest.OauthToken = userCredential.Token.AccessToken;
await uploadRequest.UploadAsync();
//uploadRequest.UploadAsync();
if (fileStream != null)
{
fileStream.Dispose();
}
Did you try this same code for the older bucket and it worked? It seems to me that there is an issue with line of code, uploadRequest.OauthToken = userCredential.Token.AccessToken. You are calling the Token.AccessToken directly from the userCredentials. These methods should be called from the userCredentials.Result.
I am trying to find an example of uploading a file to an Azure file share from a razor page. I would like to be able to select a file and then have that file saved to the share. I am using Visual Studio 2017, .Net Core 2.0. The only examples I am finding are for Blob storage. Any help would be much appreciated.
[HttpPost]
public IActionResult Index(Microsoft.AspNetCore.Http.IFormFile files)
{
string storageConnectionString = "connectionstring to your azure file share";
CloudStorageAccount cloudStorageAccount = CloudStorageAccount.Parse(storageConnectionString);
CloudFileClient cloudFileClient = cloudStorageAccount.CreateCloudFileClient();
CloudFileShare cloudFileShare = cloudFileClient.GetShareReference("your file share name");
cloudFileShare.CreateIfNotExistsAsync();
CloudFileDirectory rootDirectory = cloudFileShare.GetRootDirectoryReference();
CloudFile file = rootDirectory.GetFileReference(files.FileName);
TransferManager.Configurations.ParallelOperations = 64;
// Setup the transfer context and track the upoload progress
SingleTransferContext context = new SingleTransferContext();
using (Stream s1 = files.OpenReadStream())
{
var task = TransferManager.UploadAsync(s1, file);
task.Wait();
}
return RedirectToPage("/Index");
}
Here is a simple method I'm using to upload a single file to an endpoint.
[HttpPost]
public async Task<IActionResult> Upload(IFormFile file)
{
if (file != null)
{
using (var stream = new MemoryStream())
{
try
{
// assume a single file POST
await file.CopyToAsync(stream);
stream.Seek(0, SeekOrigin.Begin);
// now send up to Azure
var filename = file.FileName;
var storageAccount = CloudStorageAccount.Parse(<YOUR CREDS HERE>);
var client = storageAccount.CreateCloudFileClient();
var shareref = client.GetShareReference("YOUR FILES SHARE");
var rootdir = shareref.GetRootDirectoryReference();
var fileref = rootdir.GetFileReference(filename);
await fileref.DeleteIfExistsAsync();
await fileref.UploadFromStreamAsync(stream);
return Ok(new { fileuploaded = true });
}
catch (Exception ex)
{
return BadRequest(ex);
}
}
}
else
{
return BadRequest(new { error = "there was no uploaded file" });
}
}
I'm trying to use Windows Azure Storage for my Windows Store App with Mobile Services to store images. I made uploading work by following this guide:
http://www.windowsazure.com/en-us/develop/mobile/tutorials/upload-images-to-storage-dotnet/
However, I couldn't find any material on downloading the files. I couldn't even find classes reference for windows store version! If someone could guide me to the documentation I would be grateful.
Anyway, I wrote the code but it doesn't seem work:
public static async System.Threading.Tasks.Task DownloadUserImage(SQLUser userData)
{
var usersFolder = await GetUsersFolder();
var imageUri = new Uri(userData.ImageUri);
var accountName = "<SNIP>";
var key = "<SNIP>";
StorageCredentials cred = new StorageCredentials(accountName, key);
CloudBlobContainer container = new CloudBlobContainer(new Uri(string.Format("https://{0}/{1}", imageUri.Host, userData.ContainerName)), cred);
CloudBlockBlob blob = container.GetBlockBlobReference(userData.ResourceName);
var imageFile = await usersFolder.CreateFileAsync(userData.Id.ToString() + ".jpg", CreationCollisionOption.ReplaceExisting);
using (var fileStream = await imageFile.OpenAsync(FileAccessMode.ReadWrite))
{
try
{
await blob.DownloadToStreamAsync(fileStream);
}
catch (Exception e)
{
Tools.HandleLiveException(e);
}
}
}
This code results in empty file creation, but it doesn't throw any exceptions whatsoever. If I paste the value of imageUri to my browser, it starts downloading the file and completes the download successfully. However, my program does not, for some reason.
Any help, please?
Apparently, I've been opening the stream in a wrong way. Here's a fix:
public static async System.Threading.Tasks.Task DownloadUserImage(SQLUser userData)
{
var usersFolder = await GetUsersFolder();
var imageUri = new Uri(userData.ImageUri);
var accountName = "<SNIP>";
var key = "<SNIP>";
StorageCredentials cred = new StorageCredentials(accountName, key);
CloudBlobClient client = new CloudBlobClient(new Uri(string.Format("https://{0}", imageUri.Host)), cred);
CloudBlobContainer container = client.GetContainerReference(userData.ContainerName);
var blob = await container.GetBlobReferenceFromServerAsync(userData.ResourceName);
var imageFile = await usersFolder.CreateFileAsync(userData.Id.ToString() + ".jpg", CreationCollisionOption.ReplaceExisting);
using (var fileStream = await imageFile.OpenStreamForWriteAsync())
{
try
{
await blob.DownloadToStreamAsync(fileStream.AsOutputStream());
}
catch (Exception e)
{
Tools.HandleLiveException(e);
}
}
}
It works perfectly now.