interacting with blob storage on MS Azure from ASP.NET C# - c#

I am working on a website, I should deploy this on Azure cloud after I finish development, the thing is that my web app should upload a blob from the user local machine to the blob storage
my question is , how do I get the file path of the file?
I use upload control to enable the user to upload a file
when the user clicks the submit button there is code executed to upload the file specified in the upload control to the blob storage
how can I get the value of the filepath variable in my code?
does the file need to be uploaded on the server that is hosting my web app, or I can just use the path of the file from the client's local machine?
this is the upload web form code:
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Auth;
using Microsoft.WindowsAzure.Storage.Blob;
using Microsoft.Azure;
namespace myProject
{
public partial class popout : System.Web.UI.Page
{
protected void Button1_Click(object sender, EventArgs e)
{
string filePath;
if (FileUpload1.PostedFile != null)
{
filePath = FileUpload1.PostedFile.FileName;
}
else { filePath = null; }
// file name with path of the file uploaded using FileUpload1 control
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("connectionstringWhatever"));
// Create a blob client.
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
// Get a reference to a container named “myContainer”
CloudBlobContainer container = blobClient.GetContainerReference("myContainer");
//setting the permission to public
container.SetPermissions(new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob });
// Retrieve reference to a blob named "blob1".or if doesn't exist, create one
CloudBlockBlob blockBlob = container.GetBlockBlobReference("blob1");
if (filePath != null)
{
using (var fileStream = System.IO.File.OpenRead(filePath))
{
blockBlob.UploadFromStream(fileStream);
}
}
else {
string msg = "FileUpload1 = null";
ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + msg + "');", true);
}
}
}
}

Take a look at this page on MSDN, particularly the example:
https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.fileupload.postedfile(v=vs.110).aspx
This is a similar scenario to yours. The example saves the uploaded file to the server, then performs additional operations on it. However, you may also be able to write the file data to the blob so long as the file data is in memory, using the PostedFile property.
You won't be able to provide the file path to the file on the user's machine. The upload path is provided through the upload dialog only; you don't have access to that path from your application.

Related

Uploading File to Azure Blob Storage results in size 0

Able to successfully create a container and upload any file in a created container. Having an issue after downloading a file (any uploaded file) they are always zero. Here is my code using C# in a NET.Core application.
// Get a reference to a blob
BlobContainerClient container = new BlobContainerClient(connectionString: connectionString, blobContainerName: "test-container");
await container.CreateIfNotExistsAsync();
try
{
// Get a reference to a blob
BlobClient blob = container.GetBlobClient(uploadFiles.First().FileName);
string filePath = Path.GetFullPath(uploadFiles.First().FileName);
// Upload file data
await blob.UploadAsync(filePath, true);
}
catch (Exception e)
{
_ = e;
}
enter image description here
Image is attached to show what is inside the Auzure portal storage account, the size there is ZERO ?!
I am following documentation from Microsoft and they are also not setting any size explicitly when uploading a file.
The following code can work:
using FileStream uploadFileStream = File.OpenRead(filePath);
await blob.UploadAsync(uploadFileStream, true);
uploadFileStream.Close();

file saved path on Azure

I'm new to .NET Core and Azure I have created an API with SQL-Server and I used Dapper for saving the path to the database for POST form-data with an image, like this:
private async Task<string> WriteFile(Image image)
{
String fileName;
IFormFile file = image.image;
long Id = image.ShopId;
try
{
var extension = "." + file.FileName.Split('.')[file.FileName.Split('.').Length - 1];
fileName = Guid.NewGuid().ToString() + extension;
var path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot\\cccc", fileName);
using (var bits = new FileStream(path, FileMode.Create))
{
await file.CopyToAsync(bits);
}
Image imageupload = new Image(path,Id);
toDb(imageupload);
}
catch (Exception e)
{
return e.Message;
}
return fileName;
}
public void toDb(Image imageUpload)
{
string path = imageUpload.path;
long ShopId = unchecked((int)imageUpload.ShopId);
using (IDbConnection dbConnection = Connection)
{
string sQuery = "UPDATE shop SET path = #path WHERE ShopId = #ShopId ;";
dbConnection.Open();
dbConnection.Execute(sQuery, new {path = path,ShopId = ShopId});
}
}
Before I deployed to Azure it returned image path "F:\\xxxx\\yyyyy\\zzzzzz\\aaaaaa\\wwwroot\\bbbbbb\\5d665cbc-679d-4926-862b-4e10f9358e8a.png"
After i deployed it return my image path
D:\\home\\site\\wwwroot\\wwwroot\\Shops\\a81c757e-df7e-4cf6-b778-20fc5fcf922d.png
can i view image by using this path if it possible how it view;
If the error is my path that file tried to save to how can I fix it? If I changed saved path to wwwroot\\bbbbbb\\5d665cbc-679d-4926-862b-4e10f9358e8a.png can I viewed file it from client app if its also not possible. How can i fixed this?
can i view image by using this path if it possible how it view.
Yes, in the Azure WebApp D:\home is shared for us. We could get more information about Azure WebApp Sandbox from this tutorial.
We could use the Kudu(To access your KUDU console, using your DEPLOYMENT credentials, navigate to https://*****.scm.azurewebsites.net where ***** is the name of your Web App.) to view, upload or download the files.
We also could use the FTP tool to download or upload the files to Azure WebApp site.
can I viewed file it from client app if its also not possible. How can i fixed this?
I recommand that you could store the image information to Azure storge. It is easy for us to access from client side. For more information about how to use Azure Storage, please refer to this document.

Download file in azure storage using ASP.Net core2

I have web application and user should be able to download files which are stored in the azure storage.
public class FileDownloader
{
private string constring = "myconnectionstring";
public async Task download(string fileName, string directoryName)
{
try
{
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(constring);
CloudFileClient fileClient = storageAccount.CreateCloudFileClient();
CloudFileShare share = fileClient.GetShareReference("myreference");
string userName = Environment.UserName;
if (await share.ExistsAsync())
{
// Get a reference to the root directory for the share.
CloudFileDirectory rootDir = share.GetRootDirectoryReference();
// Get a reference to the directory we created previously.
CloudFileDirectory sampleDir = rootDir.GetDirectoryReference(directoryName);
// Ensure that the directory exists.
if (await sampleDir.ExistsAsync())
{
// Get a reference to the file we created previously.
CloudFile file = sampleDir.GetFileReference(fileName);
// Ensure that the file exists.
if (await file.ExistsAsync())
{
await file.DownloadToFileAsync(string.Format("C:/Users/" + userName + "/Downloads/{0}", fileName), FileMode.Create);
}
}
}
}
catch (Exception ex)
{
}
}
}
This is my code.
It works perfectly when I run application in my local environment(localhost) but when I deploy it and host it in the azure, it isn't downloading the files.
DownloadToFileAsync() : it allows you to download the file in the directory of your application not client.
May be use a stream to download it ?
How to download files from Azure Blob Storage with a Download Link

How to upload a file in to azure blob in Asp.Net Core?

I have tried to upload the files in to my azure blob using below code
public async void UploadSync(IEnumerable<IFormFile> files, string path)
{
string MyPath = path.Replace("https://browsercontent.blob.core.windows.net/blob1/", "");
try
{
foreach (var file in files)
{
var newBlob = container.GetBlockBlobReference(MyPath);
await newBlob.UploadFromFileAsync(#"C:\Users\joy\Downloads\" + file.FileName);
}
}
catch (Exception ex)
{ throw ex;}
}
Actually i have upload the jpg file but it upload in a "application/octact steam" type. how to resolve it?
And my scenario is while uploading the file, windows explorer will open to select the file to upload. So if we provide the path as static as below,
newBlob.UploadFromFileAsync(#"C:\Users\joy\Downloads\" + file.FileName);
it will not be applicable for application. How to change this code to upload the files from various locations?
Try to use UploadFromStream and let me know the outcome
// Retrieve storage account from connection string.
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
    CloudConfigurationManager.GetSetting("StorageConnectionString"));
// Create the blob client.
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
// Retrieve reference to a previously created container.
CloudBlobContainer container = blobClient.GetContainerReference("mycontainer");
// Retrieve reference to a blob named "myblob".
CloudBlockBlob blockBlob = container.GetBlockBlobReference("myblob");
// Create or overwrite the "myblob" blob with contents from a local file.
using (var fileStream = System.IO.File.OpenRead(#"path\myfile"))
{
    blockBlob.UploadFromStream(fileStream);
}
https://learn.microsoft.com/en-us/azure/storage/blobs/storage-dotnet-how-to-use-blobs

Can enumerate and see blob in storage account but cannot access it

I'm working out of my local VS (2013 for one project, 2015 for the other.)
I'm new to blobs and security, I had to pick up someone else's project which had slow upload speeds because they were uploading from the client browser to blob storage, and then taking the blob, creating a media asset and encoding the asset as mp4. Well I'm trying to put the encoding and creation of the media asset into a background process.
When I run localhost, I can upload and save to blob storage without a problem. I can see the blob in the Azure Portal, and have even set the access type on the blob to container. But when I try to retrieve the blob from background storage, it looks like I am getting a handle to the blob, but when I try to make a call to blob.FetchAttributes() I get a 404. I am using the correct storage connection string. There is a SAS token added to the URL (good for 1 year) and I have tried with and without the token.
I wrote this quick console app shown below, and when the blobs in the container are enumerated I see the blob that I uploaded, and that it has the correct size. Yet the call to blob.Exists() fails everytime. The redacted URL I am using for the fileName var to get the blob reference is being copied directly from the Azure portal. I have the correct credentials in my connection string, so I am not sure what is going on here. Any explanation would be greatly appreciated.
private static void ListBlobs()
{
CloudStorageAccount storageAccount = CloudStorageAccount.Parse( CloudConfigurationManager.GetSetting("StorageConnectionString"));
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
var container= blobClient.GetContainerReference("streamingfiles");
// Loop over items within the container and output the length and URI.
foreach (IListBlobItem item in container.ListBlobs(null, false))
{
if (item.GetType() == typeof(CloudBlockBlob))
{
CloudBlockBlob blob = (CloudBlockBlob)item;
Console.WriteLine("Block blob of length {0}: {1}", blob.Properties.Length, blob.Uri);
}
}
var fileName = "https://redacted.blob.core.windows.net/streamingfiles/47a49fb7-6f44-4f56-9695-37a4ddcd0f4a_56.mp4";//tried also with sas token
var sourceCloudBlob = container.GetBlockBlobReference(fileName);
if (sourceCloudBlob.Exists())
Console.WriteLine("Exists");
else
Console.WriteLine("Does Not Exist"); //alwayd doesn't exist
}
An alternative to container.GetBlockBlobReference(fileName).Exists();
Set the flatBlobListing flag to true, since the blob structure are of flat hierarchy.
// Loop over items within the container and output the length and URI.
foreach (IListBlobItem item in container.ListBlobs(null, true))
{
if (item.GetType() == typeof(CloudBlockBlob))
{
CloudBlockBlob blob = (CloudBlockBlob)item;
if (blob != null)
{
blob.FetchAttributes();
Console.WriteLine("Fetching Attributes");
string blobFilePath = blob.Uri.AbsolutePath.ToString();
if(String.compare(blobFilePath, filename, true) == 0)
{
Console.WriteLine("Exists");
}
else
{
Console.WriteLine("Does Not Exist")
}
Console.WriteLine("Block blob of length {0}: {1}", blob.Properties.Length, blob.Uri);
}
}
}
I'm an idiot. What's the point of passing the full path to the file when I already am in the container:
var fileName = "47a49fb7-6f44-4f56-9695-37a4ddcd0f4a_56.mp4";
Dev-One made me stop and think about it, but I can't mark that as correct.

Categories

Resources