Skip to content

Instantly share code, notes, and snippets.

@mastoj
Last active December 12, 2015 02:49
Show Gist options
  • Save mastoj/4702334 to your computer and use it in GitHub Desktop.
Save mastoj/4702334 to your computer and use it in GitHub Desktop.
private string _connectionStringKey = "MyCloudStorage";
private string _containerName = "mycontainer"; // important with lower case letters
public ActionResult Index()
{
ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
var files = GetFiles();
return View(model: files);
}
private IEnumerable<string> GetFiles()
{
var container = GetContainer();
foreach (var listBlobItem in container.ListBlobs())
{
yield return listBlobItem.Uri.AbsoluteUri;
}
}
[HttpPost]
public ActionResult Upload(HttpPostedFileBase file)
{
var container = GetContainer();
// Retrieve reference to a blob named "myblob".
CloudBlockBlob blockBlob = container.GetBlockBlobReference(file.FileName);
// Create or overwrite the "myblob" blob with contents from a local file.
using (var fileStream = file.InputStream)
{
blockBlob.UploadFromStream(fileStream);
blockBlob.Properties.ContentType = file.ContentType;
}
return RedirectToAction("Index");
}
private CloudBlobContainer GetContainer()
{
// Retrieve storage account from connection string.
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
CloudConfigurationManager.GetSetting(_connectionStringKey));
// Create the blob client.
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
// Retrieve reference to a previously created container.
CloudBlobContainer container = blobClient.GetContainerReference(_containerName);
// Create the container if it doesn't already exist.
container.CreateIfNotExists();
container.SetPermissions(new BlobContainerPermissions
{
PublicAccess =
BlobContainerPublicAccessType.Blob
});
return container;
}
<ul>
@foreach (var fileUri in Model)
{
<li>
<a href="@fileUri">@fileUri</a>
</li>
}
</ul>
@using (Html.BeginForm("Upload", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<label for="file">File:</label>
<input type="file" name="file" id="file">
<input type="submit" value="Upload">
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment